user9707187
user9707187

Reputation:

Parent process not running when calling fork(), function doesn't return

I am writing the simplest of programs using the fork() system call. When I run the program, it seems as though the parent process stops running, and the function never returns.

int main() {
    int x = 100;
    int fork_result = fork();
    if (fork_result < 0) {
        fprintf(stderr, "Fork failed.\n");
        exit(1);
    } else if (fork_result == 0) {
        printf("Child value before: %d\n", x);
        x = 200;
        printf("Child value after: %d\n", x);
    } else {
        printf("Parent value before: %d\n", x);
        x = 300;
        printf("Parent value after: %d\n", x);
    }
    return 0;
}

And the output I get when run is:

Child value before: 100
Child value after: 200

Upon which the program continues to run indefinitely without returning. What is going on here?

Thanks.

Upvotes: 0

Views: 976

Answers (2)

user9707187
user9707187

Reputation:

Found my same question here:

https://unix.stackexchange.com/questions/23228/there-is-no-bash-indicator-prompt-after-a-forked-process-terminates

This gives a good answer and seems to be what is occurring. Thanks everyone for your responses.

Upvotes: 1

Gilbert
Gilbert

Reputation: 3776

When I compiled your code it failed on compile errors due to lack of headers and a few syntax errors. Fixing those it ran as expected for me. If you have your compiler set to ignore warnings or such strange things can happen when functions are not prototyped correctly.

For educational purposes I've put a few extra lines into your code.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>

int main() {
    int x = 100;
    printf( "sizeof pid_t: %d\n", (int)sizeof(pid_t) );
    fflush( stdout );
    pid_t fork_result = fork();
    if (fork_result < 0) {
        fprintf(stderr, "Fork failed.\n");
        exit(1);
    } else if (fork_result == 0) {
        sleep(2);
        printf("Child value before: %d\n", x); 
        x = 200;
        printf("Child value after: %d\n", x); 
        printf("Child fork_result=%d\n", (int)fork_result);
        return(42);
    } else {
        printf("Parent value before: %d\n", x); 
        x = 300;
        printf("Parent value after: %d\n", x); 
        printf("Parent fork_result=%d\n", (int)fork_result);
        int   xit_stat;
        pid_t xit_wait = waitpid( fork_result, &xit_stat, 0 );
        printf("Parent sees exit=%d\n", xit_stat >> 8); 
    }   
    return 0;
}

Upvotes: 1

Related Questions