簡體   English   中英

父進程和子進程

[英]parent process, and a child process

我正在嘗試編寫一個程序,父進程將獲取main()的參數,並通過管道(每個字符一次調用write)一次一個地將字符發送到子進程。 子進程將計算父進程發送給它的字符,並打印出從父進程收到的字符數。 子進程不應以任何方式使用main()的參數。 孩子應該正常返回,而不是讓父母殺死孩子。

我在計算正確的論點嗎? 我一次發送一個論點,我是在收養孩子嗎?

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define size = 100;

int main(int argc, char *argv[])
{

    int i, count =0;
    int c;

    int     fdest[2];          // for pipe
    pid_t   pid;              //process IDs
    char    buffer[BUFSIZ];



    if (pipe(fdest) < 0)          /* attempt to create pipe */
        perror( "pipe" );

    if ((pid = fork()) < 0)  /* attempt to create child / parent process */

    {
        perror( "fork" );
    } 


    /* parent process */
    else if (pid > 0) { 

        close(fdest[0]);
        for (i=1; i < argc; ++i) 
        {
            for (c=0; c < strlen(argv[i]); ++c) {
                write(fdest[1], &argv[i][c], 1);
            }
        }

        close(fdest[1]);         
        wait(NULL);             
        exit(0);

    } else {   

        /* child Process */
        close(fdest[1]);

        while (read(fdest[0], &buffer, 1) > 0)
        {
            count++;
        }


        printf("\nchild: counted %d characters\n", count);

    }
    wait(NULL);
    exit(0);

}

第二個wait()是多余的; 孩子沒有自己的孩子等待。 第二個'退出(0);' 可以用'return(0);'代替。 您可以省略之前的'exit(0);' 太。

' #define size = 100; '是未使用的,這也是因為'='使它在大多數情況下無法使用(並且分號也是一個壞主意 - 很少用帶有分號的宏結尾)。 它應該是' #define size 100 '或' enum { size = 100 }; ”。 通常,人們使用大寫名稱來表示“清單常量”,因此' enum { SIZE = 100 };

如果您一次只讀一個字符,則實際上不需要BUFSIZ大小的緩沖區(通常為512或更大)。

另外,做' for (c = 0; c < strlen(argv[c]); c++) '是一個壞主意,因為它計算每次迭代時字符串的長度。 用以下任何一個替換它:

for (const char *str = argv[i]; *str != '\0'; str++)
    write(fdest, str, 1);

for (c = 0, len = strlen(argv[i]); c < len; c++)
      write(fdest[1], &argv[i][c], 1);

關閉管道的未使用端 - 這是使工作正常的關鍵步驟。

代碼似乎正在計數。 當我測試時,它可以下架。 為什么你懷疑它不起作用?

暫無
暫無

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

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