#include #include #include #include //unistd contains most of the Linux system calls #include #include int main (int argc, char **argv) { int pid = fork (); //In the child (new) process, fork () returns a value of 0. In the parent (original) process, fork () returns the process id number of the child. //What you normally do, is give the child its own program to run. (Not always). But this what normally happens. /* printf ("%d\n",pid); for (int i=1; i <= 10; i++) printf ("%d\n",i); */ if (pid==0) { //This is the child process /* execl ("./child","child","My","loneliness","is","killing","me",NULL); //This replaces the child's program with a new program. //The "./child" is the name of the program to be run. The second "child" is the first argument to that program, and usually matches the program name. printf ("If you like Donald Trump, don\'t say anything at all.\n"); */ int fd = open ("squareroot.in",O_RDONLY); //Open the file for reading only. The file descriptor will be some int greater than 2, because 0, 1, and 2 are already taken. dup2 (fd,0); //This assigns file descriptor 0 to point to the same file that fd points to. So standard input is now squareroot.in close (fd); //I don't need fd anymore so I close that connection but 0 (standard input) still points to that file. fd = open ("squareroot.out",O_WRONLY|O_CREAT,0700); dup2 (fd,1); close (fd); execl ("./squareroot","squareroot",NULL); //When I call execl, the running program is replaced with squareroot BUT the open files are still open and connected } else { wait (NULL); for (int i=0; i < 1/*000000*/; i++) {printf ("PARENT!\n");} } return 0; } /* Since both parent and child are running, either one might finish first. When the parent is done, the shell is going to resume control, even if the child is still running...and sending stuff in the screen. You're trying to use the shell, and the child is still running. Most of the time, you don't want this. So, traditionally, when the parent is done with what it needs to do, it waits for the child to finish before finishing itself. wait freezes the program until the child dies. If you have more than one child running, it waits until the first one dies. If you want to wait for a specific child to die, you can specify which child you want. If the parents waits as soon as it creates a child, there is no simultaneity. The child runs, and the parent will resume when the child terminates. */