日期:2014-05-16  浏览次数:20613 次

[新手求解]父子进程交替执行的问题
/*父进程每3秒创建文件, 子进程每4秒读取打印并删除文件*/

/*Include Files*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>

/*MACRO*/
#define MAX 5


/*open file, and write*/
int parent(int i)
{
int fd_write;
unsigned bytes_write;
char buf[256];
char command[256];
char path[128];

memset(buf, 0, sizeof(buf));
memset(command, 0, sizeof(command));
memset(path, 0, sizeof(path));

sprintf(path, "./%d", i);

fd_write = open(path, O_CREAT | O_WRONLY | O_TRUNC, 0640);

sprintf(buf, "%s", "This is a test.");

bytes_write = write(fd_write, buf, sizeof(buf) - 1);

close(fd_write);

printf("The write bytes are %u.\n", bytes_write);

sprintf(command, "ls -l %s", "./");

system(command);

return 0;
}


/*read file, and delete file*/
int child(int j)
{
int fd_read;
unsigned bytes_read;
char buf[256];
char command[256];
char path[128];

memset(buf, 0, sizeof(buf));
memset(command, 0, sizeof(command));
memset(path, 0, sizeof(path));

sprintf(path, "./%d", j);

fd_read = open(path, O_RDONLY);

if(-1 == fd_read)
{
perror("open error");
return -1;
}

bytes_read = read(fd_read, buf, sizeof(buf) - 1);

close(fd_read);

printf("The read bytes are %u.\n", bytes_read);

sprintf(command, "rm -f ./%d", j);

system(command);

return 0;
}

int main(int argc, char **argv)
{
pid_t pid;
int i = 0;


printf("The Current process PID = [%d]\n", getpid());

/*create first file*/
//parent(1);

/*create new process*/
pid = fork();

for(i = 1; i < MAX; i ++)
{
/*child process and the current file is the first, sleep*/
if(0 == pid && 1 == i)
{
sleep(1);
}
else if(0 == pid)
{
child(i);
sleep(2);
}
else if(pid > 0)
{
parent(i);
sleep(3);
}
else
{
printf("There was an error with forking!\n");
exit(1);
}
}

return 0;
}
程序运行时,子进程无法执行删除操作,sleep的秒数不知道怎么设置,求解进程怎么能够实现父进程创建文件,子进程刚好可以在父进程创建成功以后执行打印并删除操作 谢谢咯!

------解决方案--------------------
可以创建一个管道,用以父子进程通信
父进程创建文件之后,在管道中写入文件名称
子进程一直在阻塞读取管道,这样一旦父进程向管道写入数据,子进程就可以立即执行了
------解决方案--------------------
匿名管道可以的