Ημερήσια αρχεία: 26 Φεβρουαρίου 2016


C/C++: Pass random value from parent to child after fork() via a pipe()

The following code will create a pipe for each child, fork the process as many times as it is needed and send from the parent to each child a random int value, finally the children will read the value and terminate.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(int argc, char *argv[]) {
    int count = 3;
    int fd[count][2];
    int pid[count];
    srand(time(NULL));

    // create pipe descriptors
    for (int i = 0; i < count; i++) {
        pipe(fd[i]);
        // fork() returns 0 for child process, child-pid for parent process.
        pid[i] = fork();
        if (pid[i] != 0) {
            // parent: writing only, so close read-descriptor.
            close(fd[i][0]);

            // send the value on the write-descriptor.
            int r = rand();
            write(fd[i][1], &r, sizeof(r));
            printf("Parent(%d) send value: %d\n", getpid(), r);

            // close the write descriptor
            close(fd[i][1]);
        } else {
            // child: reading only, so close the write-descriptor
            close(fd[i][1]);

            // now read the data (will block)
            int id;
            read(fd[i][0], &id, sizeof(id));
            printf("%d Child(%d) received value: %d\n", i, getpid(), id);

            // close the read-descriptor
            close(fd[i][0]);
            //TODO cleanup fd that are not needed
            break;
        }
    }
    return 0;
}

C/C++: Pass value from parent to child after fork() via a pipe()

The following code will create a pipe, fork the process and then send from the parent to the child an int value (the id we want to give to the child), finally the child will read the value and terminate.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
	int fd[2];
	int childID = 0;

	// create pipe descriptors
	pipe(fd);

	// fork() returns 0 for child process, child-pid for parent process.
	if (fork() != 0) {
		// parent: writing only, so close read-descriptor.
		close(fd[0]);

		// send the childID on the write-descriptor.
		childID = 1;
		write(fd[1], &childID, sizeof(childID));
		printf("Parent(%d) send childID: %d\n", getpid(), childID);

		// close the write descriptor
		close(fd[1]);
	} else {
		// child: reading only, so close the write-descriptor
		close(fd[1]);

		// now read the data (will block until it succeeds)
		read(fd[0], &childID, sizeof(childID));
		printf("Child(%d) received childID: %d\n", getpid(), childID);

		// close the read-descriptor
		close(fd[0]);
	}
	return 0;
}