linux父子进程轮流交替数数,[新手求解]父子进程交替执行的问题

本帖最后由 wg4478 于 2012-03-02 17:31:38 编辑

/*父进程每3秒创建文件, 子进程每4秒读取打印并删除文件*/

/*Include Files*/

#include

#include

#include

#include

#include

#include

#include

/*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  0)

{

parent(i);

sleep(3);

}

else

{

printf("There was an error with forking!n");

exit(1);

}

}

return 0;

}

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

|

可以创建一个管道,用以父子进程通信

父进程创建文件之后,在管道中写入文件名称

子进程一直在阻塞读取管道,这样一旦父进程向管道写入数据,子进程就可以立即执行了

|

匿名管道可以的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值