After forking, are global variables shared?

No and yes. No, they are not shared in any way which is visible to the programmer; the processes can modify their own copies of the variables independently and they will change without any noticable effect on the other process(es) which are fork() parents, siblings or descendents. But yes, the OS actually does share the … Read more

Redirecting exec output to a buffer or file

For sending the output to another file (I’m leaving out error checking to focus on the important details): if (fork() == 0) { // child int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); dup2(fd, 1); // make stdout go to file dup2(fd, 2); // make stderr go to file – you may choose … Read more

Are child processes created with fork() automatically killed when the parent is killed?

No. If the parent is killed, children become children of the init process (that has the process id 1 and is launched as the first user process by the kernel). The init process checks periodically for new children, and waits for them (thus freeing resources that are allocated by their return value). The question was … Read more

fork() and output

This isn’t quite what you thought originally. The output buffer is not shared – when you execute the fork, both processes get a copy of the same buffer. So, after you fork, both processes eventually flush the buffer and print the contents to screen separately. This only happens because cout is buffered IO. If you … Read more