nonblock waitpid 非阻塞 waitpid

#include 
#include 
#include 
#include 
#include 
#include 

int main() {
    pid_t child_pid;
    int status;

    child_pid = fork();

    if (child_pid == 0) {
        // Child process
        printf("Child process executing...\n");
        sleep(2);  // Simulate some work
        exit(0);
    } else if (child_pid > 0) {
        // Parent process
        printf("Parent process executing...\n");

        // Non-blocking wait for child process
        while (waitpid(child_pid, &status, WNOHANG) == 0) {
                printf("子进程存活\n");
                sleep(1);
        }

        if (WIFEXITED(status)) {
            printf("Child process exited with status: %d\n", WEXITSTATUS(status));
        } else {
            printf("Child process did not exit normally.\n");
        }
    } else {
        // Fork failed
        printf("Fork failed.\n");
        return 1;
    }

    return 0;
}

你可能感兴趣的:(Linux)