为什么孩子在这里过程不打印任何东西?
问题描述:
假设所有的变量先前都被声明过...因为它们已经被使用过了。子进程不打印任何使我认为它没有被执行的东西。父进程运行良好,尽管它没有获得共享内存。 我对此代码的长度表示歉意...为什么孩子在这里过程不打印任何东西?
// create 5 child process
for(int k=0;k<5;k++){
// fork a child process
pid = fork();
// error occured on fork
if (pid < 0) {
fprintf(stderr, "Fork Failed");
return 1;
}
// this is what the child process will run
else if (pid == 0) {
//create a shared mem segment
segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR);
//attach the shared memory segment
shared_memory = (char *) shmat(segment_id, NULL, 0);
printf("this is child");
double x = 0;
double sum = 0;
// Run process that sums the function
for(int i=0; i<n; i++){
// get random number in range of x1-x2
x = rand()%(x2 - x1 + 1) + x1;
sum = sum + f(x);
}
//write output to the shared memory segment
sprintf(shared_memory, "%f", sum);
execlp("/bin/ls", "ls", NULL);
}
// this is what the parent process will run
else {
//print output from shared memory
printf("\n*%s", shared_memory);
//detach shared memory
shmdt(shared_memory);
//Here we add the shared memory to the array
// To add together at the end
// but since I cant get the memory to share
// the array can't be implemented
//remove the shared memory segment
shmctl(segment_id, IPC_RMID, NULL);
wait(NULL);
}
} // End of for statement
答
C stdout流在内部缓冲数据。很可能您的“这是孩子”消息正在被缓冲,缓冲区没有被execlp刷新,所以它就会消失。试试fflush(stdout);在printf之后。顺便提一句,你应该在fork()之前这样做,这样子和父都不会尝试写入从fork之前缓冲的输出。
+0
由于打印输出不包含换行符,因此成为问题的可能性很大。如果输出是行缓冲的,则换行会强制数据出现。 – 2009-02-28 01:39:08
答
先去掉所有的共享内存,然后看看子进程是否可以成功printf。
从该片段看,您正在初始化子进程中的shared_memory,但不是在父进程中。
答
打印到stderr它没有被缓冲。
fprintf(stderr,"Plop\n");
此外共享存储器的东西(SEGMENT_ID,shared_memory)在父未初始化(或者如果它是那么它是不一样的孩子)。
此外,父母可能会在孩子仍在处理时摧毁共享内存的东西。家长应该先等待,然后处理孩子生成的数据。
您不检查shm *操作的任何错误条件。 – 2009-02-28 01:35:32