Question

I'm trying to understand what the following code does:

#include <stdio.h>
#include <stdlib.h>
#include <syscall.h>
#include <unistd.h>

int main(void) {
    int pid;

    for(;;) {
        pid = fork();
        printf(getpid());

        if(pid == -1) {
            printf("fork failed");
            exit(1);
        }

        if(pid == 0) {
            execv("MYFORKAPP", NULL);
            exit(2);
        }

        wait();
    }
return 0;
}

The program itself is called MYFORKAPP. I'm learning about these 3 functions and I saw this code on the internet and I don't understand what it does.

I tried to run it (Fedora GCC) but the terminal is empty.

Should it at-least print the first getpid()?

Can you please explain me this code?

Était-ce utile?

La solution

printf(getpid());

This may crash the program. printf() expects its first argument be a string, but getpid() will return a integer, so this integer will be used as a pointer to an array of character, this very likely leads to a crash, i.e. segmentation fault.

Besides that, what this program does is

  1. fork() a child process and wait()
  2. this child process will execuate the same program again
  3. so it will fork() and wait()
  4. and so on, until your system does not have enough resource to create new process
  5. then fork() will fail, these different level child processes will exit one by one
  6. finally, the first process created by your shell will exit, and the program ends.

Autres conseils

What the following code does - segmentation fault.
Must be:

#include <stdio.h>
#include <stdlib.h>
#include <syscall.h>
#include <unistd.h>

int main(void) {
    int pid;

    for(;;) {
        pid = fork();

        if(pid == -1) {
            printf("fork failed");
            exit(1);
        }

        if(pid == 0) {
            printf("child has pid %d\n", getpid());
            execv("MYFORKAPP", NULL);
            exit(2);
        }

        wait();
    }
return 0;
}

This is a loop:
1. Parent creates a child process.
2. Child turnes to MYFORKAPP.
3. Parent wait for the child process.
4. Child terminates (may be).
5. goto 1

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top