Forking 3 processes, using shared memory - c

I have an assignment, and im beating my head against the wall. It is in C. I have a feeling im close to the solution, however I cant get the program to do whats required. I am changing the numbers and some small details, because most of the class is as stumped as I.
Requirements: Create 3 processes, the first one will increment a shared memory variable "total->value" from 1 to 10000, the second from 10000 to 12000, the third from 12000 to 14000
The process functions are labeled such (process1(), process2(), process3())
and the internals of those functions are as follows
process1()
{
int k = 0;
while (k < 10000)
{
k++;
total->value = total->value + 1;
}
printf("From process 1 = %d/n", total->value);
}
The second would be k < 2000 (because it only needs to increment the shared value 2000 more) and etc.
The main portion of the program is:
main()
{
int shmid;
int pid1;
int pid2;
int pid3;
int ID;
int status;
char *shmadd = (char *)0;
/* Create and connect to a shared memory segmentt */
if ((shmid = shmget(SHMKEY, sizeof (int), IPC_CREAT | 0666)) < 0)
{
perror("shmget");
exit(1);
}
if ((total = (shared_mem *)shmat(shmid, shmadd, 0)) == (shared_mem *)-1)
{
perror("shmat");
exit(0);
}
total->value = 0;
if ((pid1 = fork()) == 0)
process1();
if ((pid1 != 0) && (pid2 = fork()) == 0)
process2();
if ((pid1 != 0) && (pid2 != 0) && (pid3 = fork()) == 0)
process3();
if ((pid1 != 0) && (pid2 != 0) && (pid3 != 0))
{
if ((shmctl(shmid, IPC_RMID, (struct shmid_ds *)0)) == -1)
{
perror("shmctl");
exit(-1);
}
printf("\t\t End of Program.\n");
}
}
What I need is for the first process to finish, before the 2nd starts. I tried inserting a wait(&status) after the process1() (or 2 or 3) calls and am at a loss. Any pointers? (no pun intended) =) there is more to implement, but I believe once I have this part I can handle the rest on my own. I have been intentionally vague in some regards, but I would like to finish this project and more importantly understand it and there are others who want a free lunch. I will provide anything else in the code that is required. Thank you in advance for your help
The output should appear
From process 1 = 10000
From process 2 = 12000
From process 3 = 14000

I believe that Celada's comment/guess on the requirements is correct. However, barring that, and at the risk of doing too much work, the following code fulfills your spec. The use of the gcc built-in __sync_fetch_and_add() is perhaps unnecessary.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/wait.h>
static struct {
int value;
} *total;
static void process1(void) {
int k = 0;
while (k < 10000) {
k++;
__sync_fetch_and_add(&total->value, 1);
}
printf("From process 1 = %d\n", total->value); //<-- not quite right: could be >10000
}
static void process2(void) {
int k = 0;
while (__sync_fetch_and_add(&total->value, 0) != 10000)
;
while (k < 2000) {
k++;
__sync_fetch_and_add(&total->value, 1);
}
printf("From process 2 = %d\n", total->value);
}
static void process3(void) {
int k = 0;
while (__sync_fetch_and_add(&total->value, 0) != 12000)
;
while (k < 2000) {
k++;
__sync_fetch_and_add(&total->value, 1);
}
printf("From process 3 = %d\n", total->value);
}
int main(void) {
int shmid;
int pid1;
int pid2;
int pid3;
int status;
/* Create and connect to a shared memory segment */
if ((shmid = shmget(1234, sizeof *total, IPC_CREAT|0666)) < 0) {
perror ("shmget");
exit (1);
}
if ((total = shmat(shmid, 0, 0)) == (void *)-1) {
perror("shmat");
exit (0);
}
total->value = 0; // not necessary in Linux if IPC_CREAT invoked
if (!(pid1 = fork()))
process1();
else if (!(pid2 = fork()))
process2();
else if (!(pid3 = fork()))
process3();
else {
wait(&status);
wait(&status);
wait(&status);
if ((shmctl(shmid, IPC_RMID, (struct shmid_ds *) 0)) == -1) {
perror("shmctl");
exit (-1);
}
printf("\t\t End of Program.\n");
}
return 0;
}

Related

wait() gets Interupted system call

I thought that wait() fuction will wait until the proces has done, however it receives a signal -1. Does anyone know the reason of the problem? May be the problem is my shared memory? So I tried to make a debugging, and in the debbuging mode there is no problem like when I run my code in normal mode.
#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
#define PROCESSES 3
struct shdata
{
int x;
};
void childf(int shared_memory, int index)
{
// connect shared memory
struct shdata* shm = (struct shdata*)shmat(shared_memory, NULL, 0);
if(shm == (void*)-1)
{
perror("shmat");
exit(0);
}
// initialize x as 0
if(index == 0)
{
shm->x = 0;
}
// increment x
shm->x++;
//show x
printf("Proces %d: x = %d\n", index, shm->x);
// disconnect shared memory
if(shmdt(shm) == -1)
{
perror("shmdt");
exit(0);
}
// end child process
exit(0);
}
int main(int argc, const char * argv[]) {
// create shared memory
int shared_memory = shmget(IPC_PRIVATE, 4096, 0600 | IPC_CREAT | IPC_EXCL);
if(shared_memory == -1)
{
perror("shmget");
return 1;
}
// create child processes
for (int i = 0; i < PROCESSES; i++)
{
int pid = fork();
if(pid == -1)
{
perror("fork");
return 5;
}
if(pid == 0)
{
childf(shared_memory, i);
}
}
// wait for child processes
for(int i = 0; i < PROCESSES; i++)
{
int wait_res = wait(NULL);
if(wait_res < 0)
{
perror("wait");
return 6;
}
}
// delete shared memory
int delete_memory = shmctl(shared_memory, IPC_RMID, NULL);
if(delete_memory == -1)
{
perror("shmctl");
return 4;
}
return 0;
}
There what I gets:
Proces 0: x = 1 Proces 1: x = 2 Proces 2: x = 3 wait: Interrupted system call Program ended with exit code: 6
But from time to time I dont receive this error. So what is the problem?
I expected:
Proces 0: x = 1 Proces 1: x = 2 Proces 2: x = 3 Program ended with exit code: 0
An otherwise benign signal can always interrupt wait (and other blocking system calls). If you are not interested in signals, just go back to waiting.
Instead of this
wait_res = wait(NULL);
use this:
while ((wait_res = wait(NULL)) == -1) {
if (errno != EINTR) break;
}

How do I print stored data from the shared memory?

I have the following program:
#include <stdio.h>
#include <sys/types.h>
#define MAX_COUNT 100
void ChildProcess(void);
void ParentProcess(void);
void main(void)
{
pid_t pid;
pid = fork();
if (pid == 0)
ChildProcess();
else
ParentProcess();
}
void ChildProcess(void)
{
int i;
for (i = 1; i <= MAX_COUNT; i++)
printf(" This line is from child, value = %d\n", i);
printf(" *** Child process is done ***\n");
}
void ParentProcess(void)
{
int i;
for (i = 1; i <= MAX_COUNT; i++)
printf("This line is from parent, value = %d\n", i);
printf("*** Parent is done ***\n");
}
I have to modify it in a way that both the parent and the child print stored data from the shared memory in the following way:
Create and initialize the shared memory in the parent.
Fill the shared memory with 5 integer numbers. (I should allocate enough shared memory to store the 5 ints.)
Fork from the parent to the child.
If fork is successful, then the child process must print the values stored in the shared memory as shown in the expected output where N1, N2, N3, N4, N5 are the numbers found in the shared memory.
Expected output
What I did in the ParentProcess function is the following:
void ParentProcess(void)
{
int i;
for (i = 1; i <= MAX_COUNT; i++)
printf("This line is from parent, value = %d\n", i);
printf("*** Parent is done ***\n");
int localVar = 0;
int* p = (int*) malloc(2);
pid_t childPID = fork();
*p = 0;
if (childPID >= 0)
{
printf("\nChild process has started\n");
if (childPID == 0)
{
localVar++;
globalVar++;
printf("Child process has found the following data %d,", *p);
*p = 70;
printf( " %d,", *p);
*p = 66;
printf(" %d,", *p);
*p = 51;
printf(" %d,", *p);
*p = 90;
printf(" %d in shared memory\n",*p);
printf("Child is existing\n\n");
}
}
}
And now I realize that I did it completely wrong but I have no idea how to fix that. I suppose I have to use shmget to create the shared memory, but then what? How do I store values in it?
If you find that you cannot help me with this or it is too long, please share sources where I can learn more about C programming in Linux, particularly regarding the usage of shared memory. Thank you in advance
It may be better to make it clear what you want to do first because as far as I read your code you call fork() twice in your code (once in main() function and once in ParentProcess() function)
So I write general solution for parent/child shared memory. There are several ways to achieve shared memory but this is one example which is modified version of the code here
How to use shared memory with Linux in C
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/wait.h>
void *create_shared_memory(size_t size)
{
int protection = PROT_READ | PROT_WRITE;
int visibility = MAP_SHARED | MAP_ANONYMOUS;
return mmap(NULL, size, protection, visibility, -1, 0);
}
int main()
{
// Allocate 4 ints
void *shmem = create_shared_memory(sizeof(int)*4);
if( shmem == NULL ){
fprintf(stderr, "Failed to create shared memory\n");
return -1;
}
// Initialize 4 ints
((int*)shmem)[0] = 10;
((int*)shmem)[1] = 100;
((int*)shmem)[2] = 1000;
((int*)shmem)[3] = 10000;
int pid = fork();
if (pid == 0)
{
// Print 4 ints in child
printf("Child reading int 0: %d\n", ((int*)shmem)[0]);
printf("Child reading int 1: %d\n", ((int*)shmem)[1]);
printf("Child reading int 2: %d\n", ((int*)shmem)[2]);
printf("Child reading int 3: %d\n", ((int*)shmem)[3]);
printf("Child end\n");
}
else
{
printf("Parent waiting for child ends...\n");
waitpid(pid, NULL, 0);
printf("Parent ends\n");
}
int ret = munmap(shmem, sizeof(int)*4);
if( ret != 0 ){
fprintf(stderr, "Failed to unmap shared memory\n");
return -1;
}
return 0;
}
I've written a small piece of c code which you might find helpful:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#define NUM_INTS 5
int main(int argc, char *argv[])
{
key_t key = (key_t) 123456;
int shmgetrc, semgetrc;
struct shmid_ds ds;
int *shared_values;
int i;
struct sembuf sops[2];
int semid;
sops[0].sem_num = 0; /* Operate on semaphore 0 */
sops[0].sem_op = 0; /* Wait for value to equal 0 */
sops[0].sem_flg = 0;
sops[1].sem_num = 0; /* Operate on semaphore 0 */
sops[1].sem_op = 1; /* Increment value by one */
sops[1].sem_flg = 0;
/* create SHM segment */
shmgetrc = shmget(key, NUM_INTS * sizeof(int), IPC_CREAT | IPC_EXCL | 0x180);
if (shmgetrc < 0) {
perror("shmget failed...");
exit(1);
}
/* retrieve the address of the segment */
shared_values = (int *) shmat(shmgetrc, NULL, 0);
/* create a semaphore */
semgetrc = semget(key, 1, IPC_CREAT | IPC_EXCL | 0x180);
if (semgetrc < 0) {
perror("semget failed...");
exit(1);
}
/* lock the semaphore */
if (semop(semgetrc, sops, 2) == -1) {
perror("semop lock failed ...");
exit(1);
}
/* fill it with values */
for (i = 0; i < NUM_INTS; ++i) {
shared_values[i] = i;
}
/* unlock the semaphore */
sops[0].sem_op = -1;
if (semop(semgetrc, sops, 1) == -1) {
perror("semop release failed ...");
exit(1);
}
/* here something else could happen */
sleep(60);
/* lock the semaphore */
sops[0].sem_op = 0;
if (semop(semgetrc, sops, 2) == -1) {
perror("semop lock failed ...");
exit(1);
}
/* print values */
for (i = 0; i < NUM_INTS; ++i) {
printf("%d ", shared_values[i]);
}
printf("\n");
/* unlock the semaphore */
sops[0].sem_op = -1;
if (semop(semgetrc, sops, 1) == -1) {
perror("semop release failed ...");
exit(1);
}
/* remove the semaphore */
if (semctl(semgetrc, semgetrc, IPC_RMID) < 0) {
perror("semctl failed ...");
exit(1);
}
/* remove shm segment again */
if (shmctl(shmgetrc, IPC_RMID, &ds) < 0) {
perror("shmctl failed ...");
exit(1);
}
exit(0);
}
It was not my intention to write the most beautiful code ever written, just an example that shows:
how to create a shm segment
how to retrieve the address and to use it
how to remove it
Additionally, I've used a semaphore to protect the access.
Contrary to the other answer, I've used the ipc interface, not mmap().

bad file descriptor in c program with forks

this program is supposed to simulate a posix shell in regards to commands with pipes. The example I've tried to simulate and wanna make work is "ls | nl", but it doesn't and I can't figure out why. I've debugged this code for many hours with no success.
I get the error: "nl: input error: Bad file descriptor", and when I've tried not closing any of the file descriptors or closing only some (or in only one of the forks, or only the parent, etc...), and the errors change, or it works but then nl keeps waiting for input. Anyways, I'm pretty sure the errors are in fork_cmd or fork_cmds and has to do with close.
I've included all the code. I know there's nothing wrong with parser.h. I know this is pretty shitty code but it should still work I think.
I'm probably blind, but I would really appreciate it if someone could help me figure it out. Hopefully it's something that I and maybe others can learn something from.
#include "parser.h"
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <stdbool.h>
#define READ 0
#define WRITE 1
void fork_error() {
perror("fork() failed)");
exit(EXIT_FAILURE);
}
void close_error() {
perror("Couldn't close file descriptor");
exit(EXIT_FAILURE);
}
void fork_cmd(char* argv[], int n, int read_pipe[2], int write_pipe[2], int (*all_fds)[2]) {
pid_t pid;
switch (pid = fork()) {
case -1:
fork_error();
case 0:
if (read_pipe != NULL) {
if (dup2(read_pipe[READ], STDIN_FILENO) < 0) {
perror("Failed to redirect STDIN to pipe");
exit(EXIT_FAILURE);
}
}
if (write_pipe != NULL) {
if (dup2(write_pipe[WRITE], STDOUT_FILENO) < 0) {
perror("Failed to redirect STDOUT to pipe");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < n - 1; i++) {
if (close(all_fds[i][READ]) == -1 || close(all_fds[i][WRITE] == -1)) {
close_error();
}
}
execvp(argv[0], argv);
perror("execvp");
exit(EXIT_FAILURE);
default:
printf("Pid of %s: %d\n", argv[0], pid);
break;
}
}
void fork_cmds(char* argvs[MAX_COMMANDS][MAX_ARGV], int n, int (*fds)[2]) {
for (int i = 0; i < n; i++) {
if (n == 1) {
fork_cmd(argvs[i], n, NULL, NULL, fds);
}
// n > 1
else if (i == 0) {
fork_cmd(argvs[i], n, NULL, fds[i], fds);
}
else if (i == n - 1) {
fork_cmd(argvs[i], n, fds[i - 1], NULL, fds);
}
else {
fork_cmd(argvs[i], n, fds[i - 1], fds[i], fds);
}
}
for (int i = 0; i < n - 1; i++) {
if (close(fds[i][READ]) == -1 || close(fds[i][WRITE] == -1)) {
close_error();
}
}
}
void get_line(char* buffer, size_t size) {
getline(&buffer, &size, stdin);
buffer[strlen(buffer)-1] = '\0';
}
void wait_for_all_cmds(int n) {
// Not implemented yet!
for (int i = 0; i < n; i++) {
int status;
int pid;
if ((pid = wait(&status)) == -1) {
printf("Wait error");
} else {
printf("PARENT <%ld>: Child with PID = %ld and exit status = %d terminated.\n",
(long) getpid(), (long) pid, WEXITSTATUS(status));
}
}
}
int main() {
int n;
char* argvs[MAX_COMMANDS][MAX_ARGV];
size_t size = 128;
char line[size];
printf(" >> ");
get_line(line, size);
n = parse(line, argvs);
// Debug printouts.
printf("%d commands parsed.\n", n);
print_argvs(argvs);
int (*fds)[2] = malloc(sizeof(int) * 2 * (n - 1)); // should be pointer to arrays of size 2
for (int i = 0; i < n - 1; i++) {
if (pipe(fds[i]) == -1) {
perror("Creating pipe error"); // Creating pipe error: ...
exit(EXIT_FAILURE);
}
printf("pipe %d: read: %d, write: %d\n", i, fds[i][READ], fds[i][WRITE]);
}
fork_cmds(argvs, n, fds);
wait_for_all_cmds(n);
exit(EXIT_SUCCESS);
}
The problem was that one of the parenthesis was at the wrong place in both fork_cmd and fork_cmds, it should be like this of course: close(fds[i][WRITE]). This was the original code:
for (int i = 0; i < n - 1; i++) {
if (close(fds[i][READ]) == -1 || close(fds[i][WRITE] == -1))<--
{
close_error();
}
}

Semaphores with three processes

A memory location is shared by three processes. Each process independently tries to increase the content of the shared memory location from 1 to a certain value by increments of one. Process 1 has target of 100000, Process 2’s target is 200000 and the goal of 3 is 300000. When the program terminates, therefore, the shared memory variable will have a total of 600000 (i.e. this value will be output by whichever of the three processes finishes last). I am to protect the critical section using semaphores.
My problem is that I am having issues with the SETVAL for each process when initializing the semaphore. It keeps printing "Error detected in SETVAL" even though I have it set to 1. Correct sample output as well as my code is shown below:
Sample output
From Process 1: counter = 100000.
From Process 2: counter = 300000.
From Process 3: counter = 600000.
Child with ID 2412 has just exited.
Child with ID 2411 has just exited.
Child with ID 2413 has just exited.
End of Simulation.
/*ass1*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/sem.h>
#define SEMKEY ((key_t) 400L)
// number of semaphores being created
#define NSEMS 2
/* change the key number */
#define SHMKEY ((key_t) 7890)
typedef struct
{
int value;
} shared_mem;
shared_mem *total;
//structure
int sem_id, sem_id2;
typedef union{
int val;
struct semid_ds *buf;
ushort *array;
} semunion;
static struct sembuf OP = {0,-1,0};
static struct sembuf OV = {0,1,0};
struct sembuf *P =&OP;
struct sembuf *V =&OV;
//function
int Pop()
{
int status;
status = semop(sem_id, P,1);
return status;
}
int Vop()
{
int status;
status = semop(sem_id, V,1);
return status;
}
/*----------------------------------------------------------------------*
* This function increases the value of shared variable "total"
* by one with target of 100000
*----------------------------------------------------------------------*/
void process1 ()
{
int k = 0;
while (k < 100000)
{
Pop();
if (total->value < 600000) {
total->value = total->value + 1;
}
Vop();
k++;
}
printf ("From process1 total = %d\n", total->value);
}
/*----------------------------------------------------------------------*
* This function increases the vlaue of shared memory variable "total"
* by one with a target 200000
*----------------------------------------------------------------------*/
void process2 ()
{
int k = 0;
while (k < 200000)
{
Pop();
if (total->value < 600000) {
total->value = total->value + 1;
}
Vop();
k++;
}
printf ("From process2 total = %d\n", total->value);
}
/*----------------------------------------------------------------------*
* This function increases the vlaue of shared memory variable "total"
* by one with a target 300000
*----------------------------------------------------------------------*/
void process3 ()
{
int k = 0;
while (k < 300000)
{
Pop();
if (total->value < 600000) {
total->value = total->value + 1;
}
Vop();
k++;
}
printf ("From process3 total = %d\n", total->value);
}
/*----------------------------------------------------------------------*
* MAIN()
*----------------------------------------------------------------------*/
int main()
{
int shmid;
int pid1;
int pid2;
int pid3;
int ID;
int status;
char *shmadd;
shmadd = (char *) 0;
//semaphores
int semnum = 0;
int value, value1;
semunion semctl_arg;
semctl_arg.val =1;
/* Create semaphores */
sem_id = semget(SEMKEY, NSEMS, IPC_CREAT | 0666);
if(sem_id < 0)
printf("creating semaphore");
sem_id2 = semget(SEMKEY, NSEMS, IPC_CREAT | 0666);
if(sem_id2 < 0)
printf("creating semaphore");
/* Initialize semaphore */
value1 =semctl(sem_id, semnum, SETVAL, semctl_arg);
value =semctl(sem_id, semnum, GETVAL, semctl_arg);
if (value < 1)
printf("Eror detected in SETVAL");
/* Create and connect to a shared memory segmentt*/
if ((shmid = shmget (SHMKEY, sizeof(int), IPC_CREAT | 0666)) < 0)
{
perror ("shmget");
exit (1);
}
if ((total = (shared_mem *) shmat (shmid, shmadd, 0)) == (shared_mem *) -1)
{
perror ("shmat");
exit (0);
}
total->value = 0;
if ((pid1 = fork()) == 0)
process1();
if ((pid1 != 0) && (pid2 = fork()) == 0)
process2();
if ((pid1 != 0 ) && (pid2 != 0) && (pid3 = fork()) == 0 )
process3();
waitpid(pid1, NULL, 0 );
waitpid(pid2, NULL, 0 );
waitpid(pid3, NULL, 0 );
if ((pid1 != 0) && (pid2 != 0) && (pid3 != 0))
{
waitpid(pid1);
printf("Child with ID %d has just exited.\n", pid1);
waitpid(pid2);
printf("Child with ID %d has just exited.\n", pid2);
waitpid(pid3);
printf("Child with ID %d has just exited.\n", pid3);
if ((shmctl (shmid, IPC_RMID, (struct shmid_ds *) 0)) == -1)
{
perror ("shmctl");
exit (-1);
}
printf ("\t\t End of Program\n");
/* De-allocate semaphore */
semctl_arg.val = 0;
status =semctl(sem_id, 0, IPC_RMID, semctl_arg);
if( status < 0)
printf("Error in removing the semaphore.\n");
}
}
Some basics - IPCs last longer than the process so as has been mentioned use ipcs and ipcrm to delete pre-existing ipcs between runs. Make sure you delete the ipcs after execution
waitpid(pid1, NULL, 0 );
waitpid(pid2, NULL, 0 );
waitpid(pid3, NULL, 0 );
This section is going to be run for the children - they probably shouldn't.
total->value = total->value + 1;
Is not IPC safe, so different results may occur (proc1 may overwrite proc2's increment).

C fork distinguish between father and sons

My problem is the stock doesnt change i think there is something wrong in the if statement pid[i] == 0. I doenst get the prints from the "father process part" of my code only from the childs.
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <sys/types.h>
#define NUM_CHILDS 3
#define LOOPS 6
#define FILLING_UP 20
#define SHMSEGSIZE sizeof(int)
int main() {
int shmID1, shmID2, *stock, *flag, loop_i, pid[NUM_CHILDS], i;
loop_i = 1;
shmID1 = shmget(IPC_PRIVATE, SHMSEGSIZE, IPC_CREAT | 0644);
shmID2 = shmget(IPC_PRIVATE, SHMSEGSIZE, IPC_CREAT | 0644);
stock = (int *) shmat(shmID1, 0, 0);
flag = (int *) shmat(shmID2, 0, 0);
*stock = 20;
*flag = 1;
for (i = 0; i < NUM_CHILDS; i++) {
pid[i] = fork();
if(pid[i] == -1) {
printf("error by crating a child!\n\n");
return -1;
}
if (pid[i] == 0) {
printf("Child %d: %d", i, pid[i]);
while(*flag==1) {
if(*stock>0) {
*stock--;
usleep(100000);
}
}
shmdt(flag);
shmdt(stock);
return 0;
}
else {
while(loop_i <= LOOPS) {
usleep(100000);
printf("Actual stock: %d\n", *stock);
if(*stock<=0) {
*stock += FILLING_UP;
loop_i++;
printf("Stock is filled up");
}
}
*flag = 0;
}
}
for (i = 0; i < NUM_CHILDS; i++) {
waitpid(pid[i], NULL, 0);
}
printf("Programm ends", LOOPS, *stock);
shmdt(flag);
shmdt(stock);
shmctl(shmID1, IPC_RMID, 0);
shmctl(shmID2, IPC_RMID, 0);
return 0;
}
The fork() in Linux is used to create new process. Also after forking, it returns 0 in child process and returns pid of child process in parent process. So in parent process pid!=0. Hence the statement inside the if(pid==0) will not execute in parent process.
You should reset loop_i to 1. Otherwise the while loop in the parent will run LOOPS times for the first child and 0 times for the other children.
loop_i = 1;
while(loop_i <= LOOPS) {
...
}

Resources