我正在嘗試在子行程中獲取整數輸入并使用 pipe() 將其發送到父行程
但我每次在父行程中都會收到垃圾值。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
int fd[2];
char *args[] = {"", NULL};
int cnum,pnum;
pid = fork();
if (pid < 0)
{
perror("fork");
exit(1);
}
if(pipe(fd) == -1)//fd[0] for read fd[1] for write
{
perror("pipe");
exit(1);
}
if(pid == 0)
{
close(fd[0]);
printf("\n**In the child process**\n");
printf("Enter Number : ");
scanf("%d",&cnum);
write(fd[1],&cnum,sizeof(int));
close(fd[1]);
}
else
{
wait(NULL);
close(fd[1]);
printf("\n**In the parent precess**\n");
read(fd[0],&pnum,sizeof(int));
close(fd[0]);
printf("Number recieved = %d\n",pnum);
printf("PID = %d\n", getpid());
execv("./sayHello", args);
printf("Error");
}
}
上述代碼的輸出
**In the child process**
Enter Number : 212
**In the parent precess**
Number recieved = 1036468968
PID = 22528
Hillo Amol
PID = 22528
我提供了 212 的輸入,但在父級中收到了 1036468968。
uj5u.com熱心網友回復:
在創建管道 FDfork
之前呼叫。呼叫后fork
,父子節點都創建了自己的一對管道FD,并且它們之間沒有共享管道。
在分叉之前創建管道,它可以作業。
uj5u.com熱心網友回復:
正如 drorfromthenegev 建議的那樣,由于我在 fork() 之后呼叫 pipe() 而出現問題。
所以我先呼叫 pipe() 然后我呼叫 fork() 并且它有效..
可行的解決方案
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
int fd[2];
char *args[] = {"", NULL};
int cnum,pnum;
if(pipe(fd) == -1)//fd[0] for read fd[1] for write
{
perror("pipe");
exit(1);
}
pid = fork();
if (pid < 0)
{
perror("fork");
exit(1);
}
if(pid == 0)
{
close(fd[0]);
printf("\n**In the child process**\n");
printf("Enter Number : ");
scanf("%d",&cnum);
write(fd[1],&cnum,sizeof(int));
close(fd[1]);
}
else
{
wait(NULL);
close(fd[1]);
printf("\n**In the parent precess**\n");
read(fd[0],&pnum,sizeof(int));
close(fd[0]);
printf("Number recieved = %d\n",pnum);
printf("PID = %d\n", getpid());
execv("./sayHello", args);
printf("Error");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/484763.html
下一篇:PTRACE_GET_SYSCALL_INFO總是將info.op回傳為“PTRACE_SYSCALL_INFO_NONE”