子进程写入文件
问题描述:
我必须制作程序,这将使两个子进程。这些进程将在文件中写入一些东西(字符串...)。父进程应该决定其过程是要写入文件 我已创建子进程,但我停留在这些信号和我没有线索如何做到这一点子进程写入文件
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#define READY_SIGNAL SIGUSR1
#define max 1000
int main(int argc, char *argv[]) {
FILE *file;
int o;
char *name;
opterr = 0;
while ((o = getopt(argc, argv, "hp:")) != -1)
switch (o) {
case 'h':
Help();
exit(1);
default:
exit(1);
}
argc -= optind;
argv += optind;
if(argc==0){
printf("file name\n");
scanf("%s",&name);
file=fopen(name,"a+");
if(file != NULL)
{
printf("file created\n");
// fclose(file);
}
else printf("the file does not exist\n");
}
else if(argc>1) {
return(1);
}
else
meno=argv[0];
file=fopen(name,"a");
if(file != NULL){
printf("file created\n");
}
else printf("the file does not exist\n");
pid_t child_pid, child_pid2;
printf ("the main program process ID is %d\n", (int) getpid());
child_pid = fork() ;
if (child_pid != 0) {
printf ("this is the parent process, with id %d\n", (int) getpid());
printf ("the child's process ID is %d\n",(int) child_pid);
}
else {
printf ("this is the child process, with id %d\n", (int) getpid());
exit(0);
}
child_pid2 = fork() ;
if (child_pid2 != 0) {
printf ("this is the parent process, with id %d\n", (int) getpid());
printf ("the child's process ID is %d\n",(int) child_pid2);
}
else
{
printf ("this is the child process, with id %d\n", (int) getpid());
exit(0);
}
return 0;
}
感谢
答
首先你的子进程一旦创建就会退出。如果他们不这样做,那么第一个孩子会创建一个自己的孩子。你可能想在一个创建儿童for循环和做类似:
if(child_pid[i] != 0)
{
/* This is the parent. */
}
else
{
/* This is the child. */
do_child_stuff();
exit(0);
}
这是一个坏主意,你之前打开的文件叉()。您最终将拥有三个进程,这三个进程都拥有相同权限的相同文件的文件句柄。如果你这样做,生活开始变得复杂!一般情况下,只有在真正需要时才打开文件,并在完成使用后尽快关闭它们。
我觉得你的问题的意思是,你想要的父进程告诉孩子由家长发送信号给孩子写的。这样做有更简单的方法,但我想你的老师希望你演示如何用信号做到这一点。
首先,您需要编写一个信号处理程序。有关如何执行此操作的更多信息,请参阅http://linux.die.net/man/2/signal。
其次你需要真正发送信号。有关更多信息,请参阅http://linux.die.net/man/2/kill。请注意,名称“kill”有点用词不当。
如果这是功课,请标记为这样。你的问题到底是什么?你是什么意思,“卡住这些信号”?你在尝试什么,你卡在哪里? – 2010-12-06 13:48:17