标签:共享文件 shared 描述 truncate write mmap app return eof
1. fork
int pid = fork();
if (pid == -1 ) {//返回-1,说明fork失败
perror("fork");
exit(1);
} else if (pid > 0) {//返回子进程pid,说明是父进程
} else if (pid == 0) {//返回0,说明是子进程
}
fork出来的子进程和父进程相同的是:全局变量、.data、.text、堆、栈、环境变量、工作目录、宿主目录、信号处理方式等
不同的是:进程id,父进程id,定时器,未决信号集
1-1)父子进程共享文件描述符:
int test_share_fd() {
int fd = open("test_share_fd.txt", O_CREAT | O_RDWR, 0777);//在fork之前open的文件,共享fd以及文件指针offset
if (fd == -1)
{
perror("open file error");
exit(EXIT_FAILURE);
}
int pid = fork();//在fork之后open的文件,共享fd,但不共享文件指针offset
if (pid == -1)
{
close(fd);
perror("fork error");
exit(EXIT_FAILURE);
}
if (pid == 0)
{//child
char* p = "hello,share fd from child";
write(fd, p, strlen(p));
close(fd);
}
else {//parent
wait(NULL);
char buf[512];
lseek(fd, 0, SEEK_SET);
int size = read(fd, buf, sizeof(buf));
buf[size] = 0;
printf("fd from parent:%s\n", buf);
close(fd);
}
return 0;
}
1-2)父子进程共享内存mmap
int test_share_mmap() {
int len = 100;
char* filename = "test_share_mmap_temp";
int fd = open(filename, O_CREAT | O_RDWR, 0777);
if (fd == -1)
{
perror("open file error");
exit(EXIT_SUCCESS);
}
ftruncate(fd, len);
char* p = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED)
{
perror("mmap error");
exit(EXIT_FAILURE);
}
int pid = fork();
if (pid == -1)
{
munmap(p, len);
perror("fork error");
exit(EXIT_FAILURE);
}
if (pid == 0)
{
strcpy(p, "hello,share mmap from child");
}
else {
wait(NULL);
printf("mmap from parent:%s\n", p);
}
munmap(p, len);
unlink(filename);
return 0;
}
2. exec
execl,execle用于执行一个可执行文件的,比如test.exe文件
execlp用于执行一个命令行指令的,比如ls -l
int execl(const char *path, const char *arg, ... , NULL);//按路径查找,执行一个文件
//execl("/bin/ls", "ls", "-l", "-a", NULL);
//char* path = "/home/ubuntu/app/test.exe"; execl(path, path, "argv1", "argv2", NULL);
int execle(const char *path, const char *arg, ... , NULL, char * const envp[] */);//同execle
//char* _path = "/home/ubuntu/app/test.exe";
//char* _env[] = { "k1=v1","k2=v2",NULL };使用自定义env,不使用默认的extern char** environ;
//execle(_path, _path, "-l", "-a", NULL, _env);
int execlp(const char *file, const char *arg, ... , NULL);//按PATH查找,执行一个命令
//execlp("ls", "ls", "-l", "-a", NULL);
3. wait 4. waitpid
Linu创建回收进程fork、exec、wait、waitpid函数的理解
标签:共享文件 shared 描述 truncate write mmap app return eof
原文地址:https://www.cnblogs.com/yongfengnice/p/11874335.html