您的位置:首页 > 运维架构 > Linux

linux学习:进程简单操作

2014-04-25 14:15 330 查看
1、fork创建子进程:

/*
============================================================================
Name        : Test.c
Author      : wangchuan
Version     :
Copyright   : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/

#include <stdio.h>
#include <stdlib.h>

#include <fcntl.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <sys/wait.h>

int main(void) {
char buf[100]={0};
pid_t cld_pid;
int fd;
int status;
if((fd = open("temp",O_CREAT | O_RDWR | O_TRUNC,0664)) == NULL)
{
perror("创建文件");
exit(1);
}
strcpy(buf,"父进程数据");
if((cld_pid = fork()) == 0){
strcpy(buf,"子进程数据");
puts("子进程正在工作:");
printf("子进程PID是%d\n",getpid());
printf("父进程PID是%d\n",getppid());
write(fd,buf,strlen(buf));
close(fd);
exit(0);
}
else{
puts("父进程正在工作:");
printf("父进程PID是%d\n",getpid());
printf("子进程PID是%d\n",cld_pid);
write(fd,buf,strlen(buf));
close(fd);
}
wait(&status);//等待子进程结束
return 0;
}


2、创建子进程的另一种方法execve,execve系统调用与fork的不同之处在于execve创建的进程替换了原来进程的上下文,即pid保持不变

(1)在Fedora 下创建exec测试项目,编译运行,并将可执行文件复制粘贴到Test的Debug下


(2)利用execve编写系统调用函数,编译运行,但是在eclipes下看不出详细过程。



(3)所以我们在命令行下进行,可以看到更加详细的过程。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: