- 论坛徽章:
- 0
|
这个是在去年看linux的进程通信后,写的一个,正在慢慢的学习ing...,当时的困难就是不知道父子进程怎么知道对方在干什么。。
#include
#include
#include
#include
#include
#include
#include
#include
int write_file (const long line, char *fromfile, char *tofile, char *tofile2)
{
FILE *to2 = NULL;
FILE *from = NULL;
FILE *to = NULL;
int pipe_fd[2];
int r_num;
int fd;
int num;
char r_buf[1024];
char w_buf[1024];
char *buf;
struct stat n_buf;
memset (r_buf, 0x00, sizeof(r_buf));
memset (w_buf, 0x00, sizeof(w_buf));
if (pipe (pipe_fd) < 0)
{
printf ("pipe create error\n");
return -1;
}
from = fopen (fromfile, "r");
if (from == NULL)
{
printf ("Cannot open file!\n");
}
fd = open(fromfile, O_RDONLY);
fstat(fd, &n_buf);
num = n_buf.st_size;
pid_t pid;
pid = fork ();
if (pid < 0)
{
printf ("fork error\n");
}
else if (pid == 0)
{
char tmp[1024];
memset (tmp, 0x00, sizeof (tmp));
to2 = fopen (tofile2, "a+");
if (to2 == NULL)
{
printf ("Cannot open tofile2!\n");
return -1;
}
close (pipe_fd[1]);
sleep (3);
r_num = read(pipe_fd[0], r_buf, sizeof (r_buf));
fseek (from, atoi(r_buf), SEEK_SET);
for (int j = atoi(r_buf); j < num; j++)
{
if (fgets (tmp, sizeof (tmp), from) == NULL)
{
printf ("read to2file error [%s]\n", strerror (errno));
return -1;
}
fputs (tmp, to2);
}
}
else
{
char tmp1[1024];
memset (tmp1, 0x00, sizeof (tmp1));
to = fopen (tofile, "a+");
if (to == NULL)
{
printf ("Cannot open tofile!\n");
return -1;
}
for (int i = 0; i < line; i++)
{
if (fgets (tmp1, sizeof (tmp1), from) == NULL)
{
printf ("read file error [%s]\n", strerror (errno));
return -1;
}
fputs (tmp1, to);
}
//取出父进程读的字节数
fseek (from, 0, SEEK_CUR);
long last = ftell(from);
close (pipe_fd[0]); //关闭读
snprintf(w_buf,sizeof(w_buf),"%ld",last);
if (write (pipe_fd[1], w_buf, sizeof (w_buf)) != -1)
{
printf ("Write over!\n");
}
close (pipe_fd[1]);//关闭写
sleep (1);
}
if (to != NULL)
fclose (to);
if (to2 != NULL)
fclose (to2);
if (from != NULL)
fclose (from);
return 0;
}
int main ()
{
char fromfile[] = "file1";
char tofile[] = "file2";
char to2file[] = "file3";
long b = 3;
write_file (b, fromfile, tofile, to2file);
return 0;
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/8201/showart_244595.html |
|