簡體   English   中英

在父子進程之間創建管道

[英]creating pipe between father and child process

我正在嘗試在父子進程之間創建管道。 在此管道中,子進程將寫入數據,而父進程將讀取並打印數據。 我不知道為什么,但是如果我輸入大字符串,則數據會出錯,對於帶有+-7個單詞的字符串,它仍然可以正常工作。 我想這大約是緩沖區的大小,但無法修復。

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

/* in this code i will make a child process with fork command
then i will create pipe using pipe commands.
i will transfer data from the child process to the father process
omriziner code
*/

void main(int argc,char *argv[])
{
    if(argc < 2){
        printf("prototype error \n<Enter any data you wana write> \n");
        return;
    }

    int fd[2]; // creating array with 2 places for 2 fd'stdio
    // fd[0] is set to read file in the pipe
    //fd[1] is set to write file in the pipe
    int piperes;
    pid_t childpid;
    char buff[5];
    char * data = "learning to the exam";
    printf("father pid %d:\n",getpid());
    printf ("size of data is %d \n",(int)sizeof(argv[1]));
    printf ("size of buff is %d \n",(int)sizeof(buff));
    piperes = pipe(fd);
    if(piperes < 0){
        perror("PIPE ERR");
        exit(1);
    }
    printf("Pipe succeed \n");
    if((childpid = fork()) == -1){ // fork will create a child process
        perror("FORK ERR");
        exit(1);
    }
// when fork  suceed - the pid of the child will return in the parent and 0 will return in the child
// when fork fail - the pid will be -1

    printf("Fork succeed, fork return is %d and process pid is %d :\n",childpid,getpid());

    if(childpid == 0){ // if pid zero , wer in the child prcs
        close(fd[0]);    
        write(fd[1],argv[1],sizeof(argv[1])); // send data to the write fd of the pipe 
        printf("data was written to fd[1] by pid : %d \n",getpid());
        exit(0);
    }
    else{ // in this case, we're in the father process
        close(fd[1]);
        read(fd[0],buff,sizeof(argv[1])+1);
        printf("Recived data is ''%s''", buff);
        printf("By pid : %d \n",getpid());
        exit(1);
    }
}
sizeof(argv[1])

這並沒有按照您的想法做。

sizeof在編譯時1求值,在這種情況下將返回8(假設您使用的是64位計算機),因為argv[1]是一個指針。

因為您需要字符串的長度(只能在運行時知道),所以應該改用:

strlen(argv[1])

1-在某些情況下, sizeof是在運行時評估的。 這不是其中的一個。

暫無
暫無

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

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