如何解决通过管道的进程间通讯发送结构
我必须显示使用管道运行命令所花费的时间,因此我使用gettimeofday函数并通过管道传递指针,但是当我在父进程中读取它时,得到的结果与预期不同。我应该得到1604626608037896,但是我有94762421350317。 这是我的代码:
if (pipe(p) < 0)
exit(1);
pid=fork();
if (pid == -1){
printf("can't fork,error occured\n");
exit(EXIT_FAILURE);
}else if (pid == 0){
//This is the child I get the time
gettimeofday(¤t,NULL);
//I write it in the pipe,if I print the time here i get the result I want
write(p[1],¤t,sizeof(current));
close(p[1]);
//then I execute the command
}else{
//this is the parent
if (waitpid(pid,&status,0) > 0){
close(p[1]);
struct timeval inicio;
//Here is the problem I think,once I tried to read it I get a random number
read(p[0],&inicio,sizeof(inicio));
printf(": %ld,%ld\n",inicio.tv_sec,inicio.tv_usec);
}else{
printf("waitpid() failed\n");
}
exit(0);
}
解决方法
我相信您期望if
块在子进程中运行,else
块在父进程中运行,并且fork
在代码段之前被调用。在这种情况下,两个过程中的p
对于两个过程而言是不同的,并且它们没有连接。
如果引发错误,请致电read
。您可以在read
系统调用中检查返回值吗?
修改后的代码片段应该看起来像
if (pipe(p) < 0)
exit(1);
if (fork() < 0)
exit(1);
if (pid == 0){
//I get the time
gettimeofday(¤t,NULL);
//I write it in the pipe,if I print the time here i get the result I want
if (write(p[1],¤t,sizeof(current)) < 0) {
perror("write");
exit(1);
}
close(p[1]);
//then I execute the command
}else{
if (waitpid(pid,&status,0) > 0){
close(p[1]);
struct timeval inicio;
//Here is the problem I think,once I tried to read it I get a random number
if (read(p[0],&inicio,sizeof(inicio)) < 0) {
perror("read");
exit(1);
}
printf(": %ld,%ld\n",inicio.tv_sec,inicio.tv_usec);
}else{
printf("waitpid() failed\n");
}
exit(0);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。