#include <mystdio.h>
int main(int argc, const char *argv[])
{
int fd_r =open("./2024.png",O_RDONLY);
if( fd_r <0)
{
printf("%d",LINE);
perror("open");
return -1;
}
int fd_w =open("./2024_fuben.png",O_WRONLY|O_CREAT|O_TRUNC,0777);
if(fd_w <0)
{
printf("%d",LINE);
perror("open");
return -1;
}
off_t size = lseek(fd_r,0,SEEK_END);
pid_t pid = fork();
if(pid>0)
{
sleep(4);
lseek(fd_r,0,SEEK_SET);
lseek(fd_w,0,SEEK_SET);
char c;
for(int i=0;i<size/2;i++)
{
read(fd_r,&c,1);
write(fd_w,&c,1);
}
printf("前半部分拷贝完毕\n");
}
else if(0 == pid)
{
char arr1[10],arr2[10],arr3[10];
sprintf(arr1,"%d",fd_r);
sprintf(arr2,"%d",fd_w);
sprintf(arr3,"%ld",size);
execl("b.out",arr1,arr2,arr3,NULL);
}
else{
perror("fork");
return -1;
}
close(fd_r);
close(fd_w);
return 0;
}
#include <mystdio.h>
int main(int argc, const char *argv[])
{
int fd_r = atoi(argv[0]);
int fd_w = atoi(argv[1]);
off_t size = atoi(argv[2]);
lseek(fd_r,size/2,SEEK_SET);
lseek(fd_w,size/2,SEEK_SET);
char c;
for(int i=0;i<size/2;i++)
{
read(fd_r,&c,1);
write(fd_w,&c,1);
}
printf("后半部分拷贝完毕\n");
return 0;
}
孤儿进程
#include <mystdio.h>
int main(int argc, const char *argv[])
{
pid_t pid = fork();
if(0 == pid)
{
while(1)
{
printf("%d %d\n",getppid(),getpid());
sleep(1);
}
}
return 0;
}
僵尸进程
#include <mystdio.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid>0)
{
while(1)
{
printf("%d %d %d\n",getpid(),pid,LINE);
sleep(1);
}
}
else if(0 == pid)
{
for(int i=0;i<3;i++)
{
printf("%d %d %d\n",getppid(),getpid(),LINE);
sleep(1);
}
exit(0);
}
else{
perror("fork");
return -1;
}
return 0;
}
守护进程
#include <mystdio.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(0 == pid)
{
//创建会话组
setsid();
//修改当前孤儿进程的运行目录
chdir("/usr");
//重设文件权限掩码
//关闭所有文件描述符
for(int i=0;i<getdtablesize();i++)
{
close(i);
}
while(1)
{
sleep(1);
}
}
return 0;
}