C 进程间通信似乎悬而未决
这是一个设计用于从程序调用中提取字符的程序,将它们一次一个地传递给子级,在子级中对它们进行计数,将该值返回给父级并打印该值。 由于某些原因,未显示输入的字符数。它编译时不会出错并运行,但不会正确退出。这让我相信,父母没有成功地收获孩子并从中获得回报C 进程间通信似乎悬而未决,c,pipe,parent-child,interprocess,C,Pipe,Parent Child,Interprocess,这是一个设计用于从程序调用中提取字符的程序,将它们一次一个地传递给子级,在子级中对它们进行计数,将该值返回给父级并打印该值。 由于某些原因,未显示输入的字符数。它编译时不会出错并运行,但不会正确退出。这让我相信,父母没有成功地收获孩子并从中获得回报 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <sys/typ
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
int main(int argc, char **argv)
{
int comm[2];
char buffer[50];
pid_t pid;
// set up pipe
pipe(comm);
// call fork()
pid = fork();
// code that runs in the child
if (pid == 0) {
// -- running in child process --
int nChars = 0;
close(comm[1]);
// Receive characters from parent process via pipe
// one at a time, and count them.
while(read(comm[0], buffer, 1) ==1) {
++nChars;
}
// Return number of characters counted to parent process.
return nChars;
}
else {
// -- running in parent process --
int nChars = 0;
int size = 0;
printf("CS201 - Assignment 3 - \n");
// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.
close(comm[0]);
for (int i = 1; i < argc ; i++) {
size = strlen(argv[i]);
for (int j = 0; j < size; j++) {
write(comm[1], &argv[i][j], 1);
}
}
// Wait for child process to return. Reap child process.
// Receive number of characters counted via the value
// returned when the child process is reaped.
wait(&nChars);
printf("child counted %d chars\n", nChars/256);
return 0;
}
}
#包括
#包括
#包括
#包括
#包括
#包括
int main(int argc,字符**argv)
{
国际通信[2];
字符缓冲区[50];
pid_t pid;
//架设管道
管道(通讯);
//调用fork()
pid=fork();
//在子系统中运行的代码
如果(pid==0){
//--在子进程中运行--
int-nChars=0;
关闭(通信[1]);
//通过管道从父进程接收字符
//一次一个,数一数。
while(读取(通信[0],缓冲区,1)==1){
++nChars;
}
//返回计数到父进程的字符数。
返回nChars;
}
否则{
//--在父进程中运行--
int-nChars=0;
int size=0;
printf(“CS201-转让3-\n”);
//从以开头的命令行参数发送字符
//argv[1]通过管道到子进程一次一个。
关闭(comm[0]);
对于(int i=1;i
您的父进程需要在完成写入后关闭管道
// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.
close(comm[0]);
for (int i = 1; i < argc ; i++) {
size = strlen(argv[i]);
for (int j = 0; j < size; j++) {
write(comm[1], &argv[i][j], 1);
}
}
close(comm[1]); // <--- add this
//从以开头的命令行参数发送字符
//argv[1]通过管道到子进程一次一个。
关闭(comm[0]);
对于(int i=1;i 关闭(命令[1]);//非常感谢你。完美地解决了我的问题。