When I create a shared memory (c program in Linux) I delete it with shmctl(shmid, IPC_RMID, 0) and everything looks fine when I'm using ipcs -m to check if there are any remaining shared memory segments. But I'm wondering how can I delete my semaphores that I've created right before the program is terminated because when I'm using ipcs -s I see both of my semaphores right there, result:
------ Semaphore Arrays --------
key semid owner perms nsems
0x6b014021 0 benjamin 600 1
0x6c014021 1 benjamin 600 1
Thanks.
You can use semget and semctl after setting KEY to the right value returned by ipcs -s:
#define KEY 0x...
int id, rc;
id = semget(KEY, 1, IPC_STAT);
if (id < 0)
{
perror("semget");
exit(1);
}
rc = semctl(id, 1, IPC_RMID);
if (rc < 0)
{
perror("semctl");
exit(1);
}
Or use directly semctl with id returned by ipcs -s:
rc = semctl(id, 1, IPC_RMID);
if (rc < 0)
{
perror("semctl");
exit(1);
}
Full C program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/sem.h>
#include <errno.h>
int main(int argc, char **argv){
int id, rc;
id = atoi(argv[1]);
printf("id=%d\n", id);
rc = semctl(id, 1, IPC_RMID);
if (rc < 0)
{
perror("semctl");
exit(1);
}
exit(0);
}
Execution:
$ ipcs -s
------ Tableaux de sémaphores --------
clef semid propriétaire perms nsems
0x00001111 393221 pifor 666 1
$ ./rsem 393221
id=393221
$ ipcs -s
------ Tableaux de sémaphores --------
clef semid propriétaire perms nsems
Related
I write a program containing two processes: the first one contains a group of two semaphores and creates the child process that reads all data in the shared memory segment and prints them.
In the second one, the child process computes the data using a compute function that returns 0 when all data are computed. It transmits them to the parent through the shared memory segment.
To write data:
On the 1st semaphore the child makes P and the parent make V.
On the 2nd semaphore the child makes V and the parent make P.
But as I'm new in this topic and still getting hardness to understand, it seems like I'm doing something wrong because it's not working as it has to be.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/shm.h>
#include <errno.h>
#include <sys/wait.h>
int sum =0;
int compute(int data){
sum += data;
return sum;
}
int main(){
int i;
int shm_id;
int data;
pid_t pid;
key_t shm_key;
sem_t *sem;
// unsigned int sem_value =2;
shm_key = ftok("/dev/null", 65);
shm_id = shmget(shm_id, sizeof(int), 0644 | IPC_CREAT);
if (shm_id < 0){
perror("shmgget");
exit(EXIT_FAILURE);
}
// data = shmat(shm_id, NULL, 0);
sem = sem_open("semaphore", O_CREAT | O_EXCL, 0644, 2);
for (i = 0; i < 2; i++){
pid = fork();
if (pid < 0)
{
perror("fork");
sem_unlink("semaphore");
sem_close(sem);
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
break;
}
}
if (pid == 0)
{
puts("Enter the data:");
scanf("%d", &data);
//child process
sem_wait(sem);
printf("Child - %d is in critical section\n", i);
sleep(1);
puts("Enter the data:");
scanf("%d", &data);
// *shrd_value += data;
printf("Child - %d: new value of data = %d\n", i, data);
printf("Child - %d: sum of whole data by far = %d\n", i, compute(data));
sem_post(sem);
exit(EXIT_SUCCESS);
}
else if (pid > 0)
{
//parent process
while (pid = waitpid(-1, NULL, 0))
{
if (errno == ECHILD)
{
break;
}
}
puts("All children exited");
shmdt(&data);
shmctl(shm_id, IPC_RMID, 0);
sem_unlink("semaphore");
sem_close(sem);
exit(0);
}
}
Output:
Enter the data:
Enter the data:
2
Child - 0 is in critical section
1Enter the data:
Child - 1 is in critical section
Enter the data:
3
Child - 0: new value of data = 3
Child - 0: sum of whole data by far = 3
2
Child - 1: new value of data = 2
Child - 1: sum of whole data by far = 2
All children exited
I have also modified the way they write to shared memory: they write directly at the address given by shmat call that is missing in your code.
I have fixed some bugs and simplifed the code (removed the array - added detailed logging especially before and after entering the critial section):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/shm.h>
#include <errno.h>
#include <sys/wait.h>
int main(){
int i;
int shm_id;
pid_t pid;
int *addr;
int data;
pid_t current_pid;
key_t shm_key;
sem_t *sem;
shm_key = ftok("/dev/null", 65);
shm_id = shmget(shm_key, sizeof(int), 0644 | IPC_CREAT);
if (shm_id < 0){
perror("shmget");
exit(EXIT_FAILURE);
}
sem_unlink("semaphore");
sem = sem_open("semaphore", O_CREAT, 0644, 1);
if (sem == SEM_FAILED) {
perror("sem_open");
exit(EXIT_FAILURE);
}
addr = (int *) shmat(shm_id, (void *) 0, 0);
if (addr == (void *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
*addr = 0;
for (i = 0; i < 2; i++){
pid = fork();
if (pid < 0)
{
perror("fork");
sem_close(sem);
sem_unlink("semaphore");
exit(EXIT_FAILURE);
}
}
if (pid == 0)
{
current_pid = getpid();
printf("Child %d: waiting for critical section \n", current_pid);
sem_wait(sem);
printf("Child %d: enters in critical section \n", current_pid);
printf("child %d: Enter the data:\n", current_pid);
scanf("%d", &data);
printf("Child %d: new value of data = %d\n", current_pid, data);
printf("Child %d: sum of whole data so far = %d\n", current_pid, *addr += data);
sem_post(sem);
printf("Child %d exits from critical section\n", current_pid);
exit(EXIT_SUCCESS);
}
else if (pid > 0)
{
//parent process
while (pid = waitpid(-1, NULL, 0))
{
if (errno == ECHILD)
{
break;
}
}
puts("All children exited");
shmdt(addr);
shmctl(shm_id, IPC_RMID, 0);
sem_close(sem);
sem_unlink("semaphore");
exit(0);
}
exit(0);
}
Note that semaphore initial value must be 1 to have a true critical section for 2 processes.
I have also removed the sleep calls and we can see that one of the process is waiting:
Child 22514: waiting for critical section
Child 22514: enters in critical section
child 22514: Enter the data:
Child 22515: waiting for critical section
333
Child 22514: new value of data = 333
Child 22514: sum of whole data so far = 333
Child 22514 exits from critical section
Child 22515: enters in critical section
child 22515: Enter the data:
666
Child 22515: new value of data = 666
Child 22515: sum of whole data so far = 999
Child 22515 exits from critical section
All children exited
All children exited
Here's the code with producer and consumer process
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> // O_CREAT, O_EXEC
#include <errno.h> // errno, ECHILD
#include <unistd.h>
#include <sys/shm.h> // shmat(), IPC_RMID
#include <sys/wait.h>
#include <semaphore.h> // sem_open(), sem_destroy(), sem_wait()...
#include <sys/types.h> // key_t, sem_t, pid_t
#include <pthread.h>
#define BUFF 10
typedef struct data{
int buff[BUFF];
int size;
int index;
}DATA;
int main(int argc, char const *argv[])
{
sem_t *full, *empty, *access;
key_t shm_key;
int shm_id;
full = sem_open ("fullname", O_CREAT , 0644, 15);
empty = sem_open ("empty", O_CREAT , 0644, 0);
access = sem_open ("access", O_CREAT , 0644, 1);
if (argc!=2)
{
exit(1);
}
int value=atoi(argv[1]);
//initialize a shared variable in shared memory
shm_key = ftok("/dev/null", 60);
shm_id = shmget(shm_key, sizeof(DATA), 0);
// shared memory error check
if (shm_id < 0){
shm_id = shmget(shm_key, sizeof(DATA), 0644 | IPC_CREAT);
DATA *data = (DATA*) shmat (shm_id, NULL, 0);
data->size=0;
data->index=0; //index
}
printf("Shared memory id: %d\n",shm_id );
printf("Checking buffer...,\n");
//If in the buffer have free space then will wait for consumer to consume the data\n"
sem_wait(empty);
printf("\nLocking buffer to produce data\n");
sem_wait(access);
//initialize a shared variable in shared memory
shm_key = ftok("/dev/null", 60);
shm_id = shmget(shm_id, sizeof(DATA), 0644 | IPC_CREAT);
// shared memory error check
if (shm_id < 0){
perror("semaphore");
exit(EXIT_FAILURE);
}
//Shared variable
DATA *data = (DATA*) shmat (shm_id, NULL, 0);
int index=(data->size + data->index) % 15;
data->buff[index]=value;
data->size++;
printf("%d is located in %d on the buffer\n",value,index );
//consusming
// attach data to shared memory
index=data->index;
value=data->buff[index];
printf("%d now consumed\n",value );
data->size--;
data->index++;
sem_post(access);
sem_post(full);
return 0;
}
select on fds higher then 255 do not check if the fd is open. Here is my example code:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/select.h>
int main()
{
fd_set set;
for(int i = 5;i<FD_SETSIZE;i++)
{
printf("--> i is %d\n", i);
FD_ZERO(&set);
FD_SET(i, &set);
close(i);
int retval = select(FD_SETSIZE, &set, NULL, NULL, NULL);
if(-1 == retval)
{
perror("select");
}
}
}
This results in:
--> i is 5
select: Bad file descriptor
...
--> i is 255
select: Bad file descriptor
--> i is 256
Then the application blocks.
Why does this not create a EBADF on 256 till FD_SETSIZE?
Requested Information from comments:
The result of prlimit is:
NOFILE max number of open files 1024 1048576
This is the result of strace ./test_select:
select(1024, [127], NULL, NULL, NULL) = -1 EBADF (Bad file descriptor)
dup(2) = 3
fcntl(3, F_GETFL) = 0x8402 (flags O_RDWR|O_APPEND|O_LARGEFILE)
fstat(3, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 2), ...}) = 0
write(3, "select: Bad file descriptor\n", 28select: Bad file descriptor
) = 28
close(3) = 0
write(1, "--> i is 128\n", 13--> i is 128
) = 13
close(128) = -1 EBADF (Bad file descriptor)
select(1024, [128], NULL, NULL, NULL
Debunking thoughts from the comments:
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/select.h>
#include <fcntl.h>
int main()
{
char filename[80];
int fd;
for(int i = 5;i<500;i++)
{
snprintf(filename, 80, "/tmp/file%d", i);
fd = open(filename, O_RDWR | O_APPEND | O_CREAT);
}
printf("--> fd is %d, FD_SETSIZE is %d\n", fd, FD_SETSIZE);
fd_set set;
FD_ZERO(&set);
FD_SET(fd, &set);
int retval = select(FD_SETSIZE, NULL, &set, NULL, NULL);
if(-1 == retval)
{
perror("select");
}
}
Results in:
$ ./test_select
--> fd is 523, FD_SETSIZE is 1024
Process exits normally, no blocking.
Something very strange is going on here. You may have found a bug in the Linux kernel.
I modified your test program to make it more precise and also to not get stuck when it hits the problem:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/time.h>
int main(void)
{
fd_set set;
struct timeval tv;
int i;
for(i = 5; i < FD_SETSIZE; i++)
{
FD_ZERO(&set);
FD_SET(i, &set);
tv.tv_sec = 0;
tv.tv_usec = 1000;
close(i);
int retval = select(FD_SETSIZE, &set, 0, 0, &tv);
if (retval == -1 && errno == EBADF)
;
else
{
if (retval > 0)
printf("fd %d: select returned success (%d)\n", i, retval);
else if (retval == 0)
printf("fd %d: select timed out\n", i);
else
printf("fd %d: select failed (%d; %s)\n", i, retval, strerror(errno));
return 1;
}
}
return 0;
}
My understanding of POSIX says that, whatever FD_SETSIZE is, this program should produce no output and exit successfully. And that is what it does on FreeBSD 11.1 and NetBSD 7.1 (both running on x86 processors of some description). But on Linux (x86-64, kernel 4.13), it prints
fd 256: select timed out
and exits unsuccessfully. Even stranger, if I run the same binary under strace, that changes the output:
$ strace -o /dev/null ./a.out
fd 64: select timed out
The same thing happens if I run it under gdb, even if I don't tell gdb to do anything other than just run the program.
Reading symbols from ./a.out...done.
(gdb) r
Starting program: /tmp/a.out
fd 64: select timed out
[Inferior 1 (process 8209) exited with code 01]
So something is changing just because the process is subject to ptrace monitoring. That can only be caused by the kernel.
I have filed a bug report on the Linux kernel and will report what they say about it.
I'm facing a synchronization problem, the problem I'm trying to solve involves sending string from parent to child, reversing it and sending it back to child ( using shared memory ).
However to make sure child is waiting for parent I'm using sleep(3) to give 3 seconds to parent process to enter string, however this is limiting my programs efficiency, I don't want to force user to wait for 3 seconds.
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/wait.h> /* Needed for the wait function */
#include <unistd.h> /* needed for the fork function */
#include <string.h> /* needed for the strcat function */
#define SHMSIZE 27
int main() {
int shmid;
char *shm;
if(fork() == 0) {
sleep(3);
shmid = shmget(29009, SHMSIZE, 0);
shm = shmat(shmid, 0, 0);
printf ("Child : Reading %s \n",shm) ;
int len=strlen(shm);
char rev[100],temp;
int i = 0;
int j = strlen(shm) - 2;
while (i < j) {
temp = shm[i];
shm[i] = shm[j];
shm[j] = temp;
i++;
j--;
}
shmdt(shm);
}else {
shmid = shmget(29009, SHMSIZE, 0666 | IPC_CREAT);
shm = shmat(shmid, 0, 0);
printf("Parent : Enter String \n ");
char *s = (char *) shm;
*s = '\0';
char a[100];
fgets(a,100,stdin);
strcat(s,a);
printf ("Parent: sending %s \n",shm);
sleep(3);
printf("Parent: receiving %s" ,shm);
shmdt(shm);
}
return 0;
}
Question:
How could this be implemented in a better way, so that the program is more efficient?
I would suggest using semaphores, this is not a case where you use 'sleep':
http://man7.org/linux/man-pages/man7/sem_overview.7.html
You can use them like in this example:
http://www.csc.villanova.edu/~mdamian/threads/posixsem.html
You cannot know for sure that it will not take more than 3 seconds, so sleep is a realy bad choice. So, it goes something like this:
#include <stdio.h>
#include <semaphore.h>
int main(void)
{
sem_t *sem = mmap(0, sizeof(sem_t), PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_ANONYMOUS, -1, 0);
sem_init(sem, 1, 1);
if(fork() == 0) {
printf("Child: Waiting to acquire semaphore\n");
sem_wait(sem);
printf("Child acquires lock\n");
/* do whatever you want then relese*/
sem_post(sem);
} else {
printf("Parent: Waiting to acquire semaphore\n");
sem_wait(sem);
printf("Parent acquires lock\n");
/* do whatever you want then relese*/
sem_post(sem);
}
sem_destroy(sem);
return 0;
}
Oh and if you want it parent to be followed by child always (or the other way around), you can use two semaphores, and initialize them accordingly(with 1 and 0, or 0 and 1).
sem_wait(sem1);
printf("Parent acquires lock\n");
/* do whatever you want then relese*/
sem_post(sem2);
/* Other things will be happening here */
sem_wait(sem2);
printf("Child acquires lock\n");
/* do whatever you want then relese*/
sem_post(sem1);
Edit
If you do not have to use shared memory, it would be better to do the communication with sockets.
Thanks to amazing StackOverflow community for coming to my rescue! I have resolved solved the issue using semaphores! I'm sharing my final code so it can be of use for anyone who gets struck in a situation like mine!
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/wait.h> /* Needed for the wait function */
#include <unistd.h> /* needed for the fork function */
#include <string.h> /* needed for the strcat function */
#include <semaphore.h>
#include <sys/mman.h>
#include<fcntl.h>
#include<stdlib.h>
#define SHMSIZE 27
typedef struct {
sem_t one;
sem_t two;
} SemPair;
int main() {
int shm = shm_open("/test", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
ftruncate(shm, sizeof(sem_t));
SemPair *sem = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, shm, 0);
sem_init(&(sem->one), 1, 0);
sem_init(&(sem->two), 1, 0);
int shmid;
char *shmz;
if(fork() == 0) {
sem_wait(&(sem->one));
shmid = shmget(29009, SHMSIZE, 0);
shmz = shmat(shmid, 0, 0);
printf ("Child : Reading %s \n",shmz) ;
int len=strlen(shmz);
char rev[100],temp;
int i = 0;
int j = strlen(shmz) - 2;
while (i < j) {
temp = shmz[i];
shmz[i] = shmz[j];
shmz[j] = temp;
i++;
j--;
}
shmdt(shmz);
sem_post(&(sem->two));
}
else {
shmid = shmget(29009, SHMSIZE, 0666 | IPC_CREAT);
shmz = shmat(shmid, 0, 0);
printf("Parent : Enter String \n ");
char *s = (char *) shmz;
*s = '\0';
char a[100];
fgets(a,100,stdin);
strcat(s,a);
printf ("Parent: sending %s \n",shmz);
sem_post(&(sem->one));
sem_wait(&(sem->two));
printf("Parent: receiving %s" ,shmz);
shmdt(shmz);
}
return 0;
}
I'm trying to migrate a multiprocess application to Docker. Different processes will be placed in different Docker container.
The application uses shared memory to exchange data and semaphores to synchronize. I already recompiled Docker in order to do not use the IPC namespace and I effectively checked with sudo ipcs -m that the shared memory buffers are accessible from the different containers.
The problem is that semaphores are not working. I wrote these simple programs to check the behavior of POSIX semaphores in Docker:
/* To be compiled with -lpthread */
#include <stdio.h>
#include <fcntl.h>
#include <semaphore.h>
int main(void) {
int ret, val;
sem_t * mySem;
printf("[ONE] Opening the semaphore...\n");
mySem = sem_open("sem1", O_CREAT, 0777, 0);
if (mySem == SEM_FAILED) {
printf("[ONE] Error on sem_open()\n");
return -1;
}
ret = sem_post(mySem);
getchar(); // Awful way to block execution of [ONE] for a while...
printf("[ONE] Waiting for [TWO]...\n");
ret = sem_wait(mySem);
printf("[ONE] Wait ended\n");
ret = sem_unlink("sem1");
printf("[ONE] Semaphore destroyed\n");
return 0;
}
The second program is:
/* To be compiled with -lpthread */
#include <stdio.h>
#include <fcntl.h>
#include <semaphore.h>
int main(void) {
int ret;
int val;
sem_t * mySem;
printf("[TWO] Opening the semaphore...\n");
mySem = sem_open("sem1", O_CREAT, 0777, 0);
if (mySem == SEM_FAILED) {
printf("[TWO] Error on sem_open()\n");
return -1;
}
ret = sem_getvalue(mySem, &val);
printf("[TWO] Semaphore's value is %d\n", val);
printf("[TWO] Waiting for [ONE]...\n");
ret = sem_wait(mySem);
printf("[TWO] Wait ended\n");
printf("[ONE] Doing sem_post() on semaphore...\n");
ret = sem_post(mySem);
ret = sem_close(mySem);
printf("[TWO] Semaphore closed\n");
return 0;
}
In both I omitted lots of controls like if (ret != 0) {...} in order to maintain readability of the question.
I run the first program on the host machine, the second one in a Docker container. The result is that the second program waits forever...
The question is: is it possible in some way to use POSIX semaphores between Docker containers or between a container and the host?
I solved the problem using shared memory between Docker containers as explained in this question.
The following code is a modified version of this tutorial.
File server.c
/* To be compiled with -lpthread */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <semaphore.h>
#define SHM_SIZE 1000
int main(void) {
int shmid;
key_t key;
char *shm;
sem_t * mySem;
/* We'll name our shared memory segment "5678" */
key = 5678;
/* Create the segment.*/
if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666)) < 0) {
perror("shmget");
exit(1);
}
/* Now we attach the segment to our data space */
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
/* Create a new semaphore */
mySem = sem_open("sem1", O_CREAT, 0777, 0);
/* Copy the semaphore on the shared memory segment */
memcpy(shm, mySem, sizeof(*mySem));
/* Do stuff ... */
/* REMEMBER TO USE THE SHARED MEMORY SEGMENT */
/* AND NOT THE LOCAL mySem, USE (sem_t*)shm INSTEAD! */
/* Finally, we wait until the other process
* changes the first character of our memory
* to '*', indicating that it has read what
* we put there.
*/
while (*shm != '*')
sleep(1);
/* Mark the memory segment to be destroyed */
shmctl(shmid, IPC_RMID, NULL);
/* Detach of the memory segment */
shmdt(&shm);
sem_unlink("sem1");
return 0;
}
File client.c
/* To be compiled with -lpthread */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>
#include <semaphore.h>
#define SHM_SIZE 1000
int main(void) {
int shmid;
key_t key;
char *shm;
int ret, val;
key = 5678;
if ((shmid = shmget(key, SHM_SIZE, 0666)) < 0) {
perror("shmget");
exit(1);
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
/* SEMAPHORE IS IN THE SHARED MEMORY SEGMENT */
/* USE (sem_t*)shm TO ACCESS IT */
*shm = '*';
shmdt(&shm);
sem_close("sem1");
return 0;
}
The code examples miss lots of controls due to readability purposes.
I run the server on the host machine, the client inside a Docker container and checked that the semaphore was accessible from both processes.
I have to make 2 processes (server/client) that can access the same shared memory. I send the keys of shared memory via UNIX sockets between the server and the client. Then, I create the shared memory segment, and use unnamed semaphores to sychronize the server/client. As I think, I do everything right, but when I run the client process I can see that the semaphore isn't even initialized!
server.c sample:
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <errno.h>
sem_t *semaphore;
int main(int argc, char **argv){
//...making the connections here
// M is the number of semaphores i will use
key_t key3;
int shmid3;
if ((shmid3 = shmget(key3, M*sizeof(sem_t), 0644 | IPC_CREAT)) == -1) {
perror("shmget3");
exit(1);
}
key3 = htonl(key3);
if (send(s2, (const char*)&key3, 4, 0) == -1) {
perror("send");
exit(1);
}
int i;
semaphore=(sem_t *)shmat(shmid3, (void *) 0, 0);
if (semaphore == (sem_t *)(-1)) perror("shmat");
for(i=0;i<M;i++) if(sem_init(&semaphore[i], 1, 1)!=0) perror("sem_init");
//..do some stuff...
sleep(3);
for(i=0;i<M;i++) sem_destroy( &semaphore[i] );
if (shmdt(semaphore) == -1) {
perror("shmdt");
exit(1);
}
shmctl(shmid3, IPC_RMID, NULL);
//close connection...
}
client.c sample:
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <errno.h>
sem_t *semaphore;
int main(int argc, char **argv){
//...making the connections here
// M is the number of semaphores i will use
key_t key3;
n = recv(s, &key3, 4, 0);
if (n < 0) {
perror("recv");
}
key3 = ntohl(key3);
int shmid3;
if ((shmid3 = shmget(key3, M*sizeof(sem_t), 0644 )) == -1) {
perror("shmget3");
exit(1);
}
semaphore=(sem_t *)shmat(shmid3, (void *) 0, 0);
if (semaphore == (sem_t *)(-1)) perror("shmat");
int value;
sleep(1);
sem_getvalue(&semaphore[0], &value);
printf("\n[%d]\n",value); //always prints 0
//...do stuff...
if (shmdt(semaphore) == -1) {
perror("shmdt");
exit(1);
}
//close connection...
}
There isn't something wrong with the UNIX connection because I share and other memory segments, and they work just fine. I also tried changing the pshared argument of sem_initbut still nothing changes in the client.
I actualy want to use the semaphores in clinet's threads(M), but I see that they do not initialize even in the main process.
(Adapting from troubleshooting in the comments...)
The uninitialized key_t key3 happens to be initialized to the value IPC_PRIVATE, which means that a new shared memory segment is created for each caller of shmget(). The key should be explicitly initialized (in this case as by ftok()).