进程(四)
fork之后父子进程共享文件

sleep可以保证子进程先结束,父进程后结束。
子进程与父进程共享文件的文件表:文件偏移值
代码示例:
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#include <unistd.h>
#include<signal.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define MAJOR(a) (int)((unsigned short)a>>8)
#define MINOR(a) (int)((unsigned short)a & 0xFF)
int filetype(struct stat * buf);
int main(int argc, char* argv[])
{
signal(SIGCHLD,SIG_IGN);
printf("befor pid=%d\n",getpid());
int fd;
fd=open("test.txt",O_WRONLY);
if(fd==-1)
ERROR_EXIT("open error");
pid_t pid1;
pid1=fork();
if(pid1>0){
printf("parent pid:%d,child pid:%d\n",getpid(),pid1);
write(fd,"parent",6);
sleep(1);
}
else if(pid1==0){
printf("child pid:%d,parent pid:%d\n",getpid(),getppid());
write(fd,"child",5);
"01fork.c" 34L, 878C written
[root@localhost 09_fork]# touch test.txt
signal(SIGCHLD,SIG_IGN);
printf("befor pid=%d\n",getpid());
int fd;
fd=open("test.txt",O_WRONLY);
if(fd==-1)
ERROR_EXIT("open error");
pid_t pid1;
pid1=fork();
if(pid1>0){
printf("parent pid:%d,child pid:%d\n",getpid(),pid1);
write(fd,"parent",6);
sleep(1);
}
else if(pid1==0){
printf("child pid:%d,parent pid:%d\n",getpid(),getppid());
write(fd,"child",5);
}
return 0;
}

fork与vfork

代码示例:
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#include <unistd.h>
#include<signal.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define MAJOR(a) (int)((unsigned short)a>>8)
#define MINOR(a) (int)((unsigned short)a & 0xFF)
int gval=100;
int main(int argc, char* argv[])
{
signal(SIGCHLD,SIG_IGN);
printf("befor pid=%d\n",getpid());
pid_t pid1;
//vfork共享地址空间,不会进行重新拷贝
pid1=vfork();
if(pid1>0){
sleep(1);
printf("parent pid:%d,child pid:%d,parent gval=%d\n",getpid(),pid1,gval);
sleep(1);
}
else if(pid1==0){
gval++;
printf("child pid:%d,parent pid:%d,child gval=%d\n",getpid(),getppid(),gval);
_exit(0);
}
return 0;
}

进程的五种终止方式


attext

#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<errno.h>
#include<string.h>
#include <unistd.h>
#include<signal.h>
#define ERROR_EXIT(m) (perror(m),exit(EXIT_FAILURE))
#define MAJOR(a) (int)((unsigned short)a>>8)
#define MINOR(a) (int)((unsigned short)a & 0xFF)
int gval=100;
void my_exit1(){
printf("my_exit1\n");
}
void my_exit2(){
printf("my_exit2\n");
}
int main(int argc, char* argv[])
{
//注册终止程序
atexit(my_exit1);
atexit(my_exit2);
exit(0);
}


新创建的进程不会从第一行代码开始运行
execve:

本文介绍了进程管理中的fork和vfork操作,以及进程如何共享文件。通过示例代码展示了父子进程如何共享文件偏移值,并探讨了进程的五种终止方式。同时,提到了进程的生命周期管理和信号处理。
447

被折叠的 条评论
为什么被折叠?



