系统编程第一天笔记
1. exec族函数
2. waitpid函数
#include <stdio.h>
#include <unistd.h>
int main()
{
//创建一个子进程
pid_t pid = fork();
if(pid == -1)//父进程里面创建子进程失败后
{
perror("fork failed");
return -1;
}
else if(pid == 0) //在子进程创建成功后,子进程里面执行的
{
printf("child:getpid():%d--getppid():%d \n", getpid(), getppid());
//execl("./printfnum", "printfnum", NULL);
//ls -l
//execl("/bin/ls", "ls", "-l", NULL);
//execlp("./printfnum", "printfnum", NULL);
//execlp("/bin/ls", "ls", "-l", NULL);
//char * const envp[]={NULL};
//execle("./printfnum", "printfnum", NULL, envp);
//execle("/bin/ls", "ls", "-l", NULL, envp);
//char *const argv[] = {"printfnum", NULL};
// execv("./printfnum", argv);
//char *const argv[] = { "ls", "-l", NULL};
//execv("/bin/ls", argv);
char *const argv[] = {"printfnum", NULL};
char *const envp[] = {NULL};
execvpe("./printfnum", argv,envp);
printf("222222222 \n");
}
else if(pid >0) //父进程里面创建子进程成功会执行
{
printf("parent:pid:%d\n", pid);
printf("parent:getpid():%d--getppid():%d \n", getpid(), getppid());
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
//创建一个子进程
pid_t pid = fork();
if(pid == -1)//父进程里面创建子进程失败后
{
perror("fork failed");
return -1;
}
else if(pid == 0) //在子进程创建成功后,子进程里面执行的
{
printf("child:getpid():%d--getppid():%d \n", getpid(), getppid());
exit(200);
}
else if(pid >0) //父进程里面创建子进程成功会执行
{
printf("parent:pid:%d\n", pid);
printf("parent:getpid():%d--getppid():%d \n", getpid(), getppid());
int status;
sleep(1);
//如果PID为pid的子进程没有退出,就结束(不阻塞)
pid_t pid1 = waitpid(pid, &status, WNOHANG);
if(pid1 == -1)
{
perror("waitpid failed");
return -1;
}
else if(pid1 >0)
{
printf("status:%d\n", status);
printf("WEXITSTATUS(status):pid:%d\t子进程的退出值:%d\n", pid, WEXITSTATUS(status));
}
else if(pid1 == 0)
{
printf("child process is running \n");
}
}
return 0;
}