Shared memory linux - c

I'm trying to work with shared memory at the first time. I created one child process and I write to the shared memory from Parent and change it from Child, before program ends I print shared memory from Parent and shared memory hasn't change, here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <signal.h>
sem_t *semaphore;
int main(){
int i = 0, status;
pid_t pid=fork(), w;
int id;
if ((id = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666)) == -1){
perror("shmget");
exit(1);
}
int *sh;
if ((sh =(int *) shmat(id, NULL, 0)) == NULL){
perror("shmat");
exit(1);
}
*sh = 10;
if ((semaphore = sem_open("/semaphore", O_CREAT, 0666, 0)) == SEM_FAILED){
perror("semaphore");
exit(1);
}
if (pid==0) {
while(1){
sleep(1);
*sh = 50;
printf("child %d, %d\n", i, *sh);
i++;
if(i == 5){
sem_post(semaphore);
exit(0);
}
}
} else if (pid==-1) {
perror("process error\n");
} else {
printf("Parent, %d\n", *sh);
sem_wait(semaphore);
printf("child end => parent end\n");
printf("Parent, %d\n", *sh);
}
shmctl(id, IPC_RMID, NULL);
sem_close(semaphore);
sem_unlink("/semaphore");
return 0;
}
If I understand shared memory little bit than I can change it from everywhere if I have a pointer in my case is a "sh".
Output of program is:
Parent, 10
child 0, 50
child 1, 50
child 2, 50
child 3, 50
child 4, 50
child end => parent end
Parent, 10
Why is the number in shared memory different in Parent and in Child?

You fork() before you create the shared memory with the key IPC_PRIVATE, so both processes create their own shared memory and don't actually share it.
If you remove the =fork() from
pid_t pid=fork(), w;
and insert
pid = fork();
somewhere after the shmget call, it works the way you expect, since the child process will inherit the shared memory identifier from the parent and not create a different one.

Related

Processes with group of 2 semaphores and shared memory

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;
}

Make fork execute equal amounts of times, infinitely

I am trying to make the following code never allow the amount of + to be greater than the amounts of - . I am thinking about adding a simple line of just c sleep(1) but I was curious to see if there is a better way to make the amounts equal. This is supposed to stay an infinite loop.
int main(){
if(fork() ==0)
while(1){
write(1,"-",1)
}
else
while(1){
write(1, "+",1);
}
return 0;
}
Would this function correctly using semaphores?
int main(){
int parent_sem = get_semaphore(0);
int child_sem = get_semaphore(1);
if(fork() ==0)
while(1){
sem_wait(child_sem);
write(1,"-",1);
sem_signal(parent_sem);
}
else
while(1){
sem_wait(parent_sem);
write(1, "+",1);
sem_signal(child_sem);
}
return 0;
}
Here's a fixed version of your semaphore example. I have allocated shared memory so that the semaphores can be accessed by both processes across the fork (I forgot this was necessary, sorry) and fixed the semaphore types and calls.
#include <unistd.h>
#include <semaphore.h>
#include <sys/mman.h>
int main() {
// Create shared memory for two semaphores
sem_t* sem = mmap(NULL, 2 * sizeof(sem_t), PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
// Initialise parent and child semaphores: parent = 1, child = 0
sem_t* parent_sem = sem;
sem_t* child_sem = sem + 1;
sem_init(parent_sem, 1, 1);
sem_init(child_sem, 1, 0);
if (fork() == 0) {
while(1) {
// Child process
sem_wait(child_sem);
write(1, "-", 1);
sem_post(parent_sem);
}
} else {
while(1) {
// Parent process
sem_wait(parent_sem);
write(1, "+", 1);
sem_post(child_sem);
}
}
return 0;
}
This is close (Use signals):
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
void usr1handler() {
}
int main(void) {
int pid;
signal(SIGUSR1, usr1handler);
if ((pid = fork()) == 0) {
while (1) {
pause();
write(1, "-", 1);
fflush(stdout);
kill(getppid(), SIGUSR1);
}
}
else {
sleep(1);
while (1) {
write(1, "+", 1);
fflush(stdout);
kill(pid, SIGUSR1);
pause();
}
}
}
The main issue for this is the race condition. If a process makes it to the kill() function before the other makes it to the pause(), the program freezes. This is probably good enough to start you off though. I left a single sleep in there so you could see that it does indeed print evenly.

What alternatives I have against sleep() to synchronize transfer between parent and child process?

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;
}

Shared Memory - Sons generate numbers and father sum the results [ UNIX ]

I am trying to create a small program that creates two sons ( proccess ), each son generate random number. the father wait for the sons and sum the results.
The Question: What is the modifications I need to do to make it work?
this is what I did so far.
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define SEGSIZE 100
void main()
{
key_t key;
int shmid;
char *segptr;
int status=0;
int r_pid=1;
int r_pid2=1;
key = ftok(".", 'T');
if((shmid = shmget(key, SEGSIZE,IPC_CREAT|IPC_EXCL|0666))== -1)
{
printf("Shared memory segment exists - opening as client\n");
if((shmid = shmget(key, SEGSIZE, 0)) == -1)
{
perror(" bad shmget");
exit(1);
}
}
else
{
printf("Creating new shared memory segment\n");
}
if((segptr = shmat(shmid, 0, 0)) == NULL)
{
perror("shmat");
exit(1);
}
r_pid=fork();
if(r_pid!=0)
r_pid2=fork();
if(r_pid<0 || r_pid2<0 )
{
printf("No child created");
exit(1);
}
if(r_pid==0 )
{
printf("The child process with PID number : %d"" (his parent PID is %d) writes a text to the shared"" memory\n",getpid(),getppid());
strcpy(segptr,"12");
}
else if(r_pid2==0)
{
segptr+=2;
printf("The child process with PID number : %d" " (his parent PID is %d) writes a text to the shared"" memory\n",getpid(),getppid());
strcat(segptr,"14");
}
else
{
r_pid = wait(&status);
r_pid2 = wait(&status);
printf(" The following text is received by the ""parent process with PID number pid: %d pid2 : %d text: %s\n",r_pid,r_pid2,segptr);
}
shmctl(shmid, IPC_RMID, 0);
}
Suggestions Are Welcomed! thanks.
EDIT
Here is some update:
If I initialize segptr with useless chars like: strpy(segptr,"a")
and then in the sons I do strcat(segptr,"test1") and in r_pid2 I do strcat(segptr,"test2")
the father will print test1test2 or vice versa.
There is no guarantee that the first child runs before the second. So, the
segptr+=2;
…
strcat(segptr,"14");
may be executed before
strcpy(segptr,"12");
causing the first digit of "14" to be overwritten by the terminating null character of "12".
What is the modifications I need to do to make it work?
Make sure that the writes do not overlap, e. g. by changing the
strcpy(segptr,"12");
to
strncpy(segptr, "12", 2);

Creating multiple children of a process and maintaining a shared array of all their PIDs

I have forked a couple of times and have created a bunch of child processes in C. I want to store all their PIDs in a shared array. The ordering of the PIDs does not matter. For instance, I created 32 processes. I would like to have a 32 integer long array that would store each of their PIDs and is accessible to each of these processes. What could be the best way to do this.
Here's a program that illustrates what you want using mmap():
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PIDS 32
volatile pid_t *pids;
// Called for each child process
void do_child(void)
{
int c;
printf("Child: %d - pid array: ", getpid());
for (c=0; c<10; c++) {
printf("%d%s", pids[c], c==9?"\n":" ");
}
}
int main(int argc, char **argv)
{
int c;
pid_t pid;
// Map space for shared array
pids = mmap(0, MAX_PIDS*sizeof(pid_t), PROT_READ|PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (!pids) {
perror("mmap failed");
exit(1);
}
memset((void *)pids, 0, MAX_PIDS*sizeof(pid_t));
// Fork children
for (c=0; c<10; c++) {
pid = fork();
if (pid == 0) {
// Child process
do_child();
exit(0);
} else if (pid < 0) {
perror("fork failed");
} else {
// Store in global array for children to see
pids[c] = pid;
sleep(1);
}
}
exit(0);
}

Resources