簡體   English   中英

C:父子流程

[英]C: Parent and Child Processes

我正在嘗試執行以下操作...

Create a new process
obtain the PID of a process
put a process to sleep for a defined period of time
check process ID on the terminal 

我的程序運行了,但是輸出不是我期望的那樣,而且我不確定我要去哪里。 感謝您的寶貴時間,我非常感謝!

碼:

int main() {
    int i;
    pid_t pid=0;

    /** use fork() system call to create a new process */
    /** if the pid returned by fork() is negative, it indicates an error */

    if(fork()<0) {
        perror("fork");
        exit(1);
    }

    if(pid==0) {
        printf("child PID= %d\n", (int) getpid());
        for(i=0; i<10; i++) {
            printf("child: %d\n", i);
            /** put process to sleep for 1 sec */
            sleep(1);
        }
    } else {
        /* parent */
        /** print the parent PID */
        printf("parent PID= %d\n", (int) getpid());
        for(i=0; i<10; i++) {
            printf("parent: %d\n", i);
            sleep(1);
        }
    }

    exit(0);
}

輸出應該看起來像...

parent PID=8900
child PID=4320
parent:0
child:0
child:1
parent:1
child:2
parent:2
child:3
parent:3
parent:4
etc.

但是我要...

child PID= 97704
child: 0
child PID= 106388
child: 0
child: 1
child: 1
child: 2
child: 2
child: 3
child: 3
child: 4
child: 4
child: 5
child: 5
child: 6
child: 6
child: 7
child: 7

您實際上並沒有將fork()的輸出分配給pid,因此pid保持為零。

如上所述,您沒有將pid分配給任何內容,因此它始終為零。 您還應該將條件更改為pid而不是調用另一個fork()

int main() {
int i;
pid_t pid=0;

pid = fork(); /* Add this */

/** use fork() system call to create a new process */
/** if the pid returned by fork() is negative, it indicates an error */

if(pid<0) { /* Change this */
    perror("fork");
    exit(1);
}

另外,如果您的預期輸出看起來仍然與預期有所不同,請不要感到驚訝。 沒有辦法告訴孩子或父母何時會被叫(特別是您是否睡了)。 這取決於各種各樣的事情。

編輯:我明白你在說什么。 您想通過終端檢查進程ID嗎? 您可以添加一個getchar(); 到程序末尾以暫停程序退出,則可以打開另一個終端並運行ps 您需要確保添加#include <stdio.h> ,但要使用它。

使用pid進行比較,而不是調用另一個fork() 設置pid等於fork()以便您可以對其進行比較以檢查pid錯誤。

int main() {
    int i;
    pid_t pid=0;
    pid = fork();

    /** use fork() system call to create a new process */
    /** if the pid returned by fork() is negative, it indicates an error */

    if(pid<0) {
        perror("fork");
        exit(1);
    }

    if(pid==0) {
        printf("child PID= %d\n", (int) getpid());
        for(i=0; i<10; i++) {
            printf("child: %d\n", i);
           /** put process to sleep for 1 sec */
            sleep(1);
        }
    } else {
       /* parent */
        /** print the parent PID */
        printf("parent PID= %d\n", (int) getpid());
        for(i=0; i<10; i++) {
            printf("parent: %d\n", i);
            sleep(1);
       }
    }

    exit(0);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM