fork:
fork与进程创建有关:
fork函数在进程中创建子进程
子进程复制父进程的pcb -------代码共享, 数据独有
#include <unistd.h>
pid_t fork(void);
#include<unistd.h>
#include<stdio.h>
#include<wait.h>
#include<error.h>
#include<stdlib.h>
int main()
{
int pid = fork();
if(pid < 0)
{
perror("fork error");
exit(-1);
}else if(pid == 0) //子进程
{
printf("pid = %d\n",pid); //子进程中pid的值
printf("child : %d\n",getpid()); //子进程的pid
}else
{
wait(NULL); //保证子进程先于父进程退出
printf("pid = %d\n",pid) //父进程中pid的值
printf("parents : %d\n",getpid());
}
return 0;
}
fork调用返回值
1)在父进程中,fork返回新创建子进程的进程ID;
2)在子进程中,fork返回0;
3)如果出现错误,fork返回一个负值;
popen:
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
popen()函数:创建一个管道用于进程间通信,并调用shell,因为管道被定义为单向的 所以 type 参数 只能定义成 只读或者 只写, 不能是 两者同时, 结果流也相应的 是只读 或者 只写.
函数功能:popen()会调用fork()产生子进程,然后从子进程中调用/bin/sh -c来执行参数command的指令。这个进程必须由 pclose 关闭。
#include<stdio.h>
int main()
{
FILE *fd = popen("ls","w");
pclose(fd);
return 0;
}
command参数:
command 参数 是 一个 字符串指针, 指向的是一个 以 null 结束符 结尾的字符串, 这个字符串包含 一个 shell 命令. 这个命令 被送到 /bin/sh 以 -c 参数 执行, 即由 shell 来执行.
type 参数 也是 一个 指向 以 null 结束符结尾的 字符串的指针
参数type可使用“r”代表读取,“w”代表写入。
依照此type值,popen()会建立管道连到子进程的标准输出设备或标准输入设备,然后返回一个文件指针。
随后进程便可利用此文件指针来读取子进程的输出设备或是写入到子进程的标准输入设备中。
返回值:
若成功则返回文件指针,否则返回NULL,错误原因存于errno中.
system:
#include <stdlib.h>
int system(const char *command);
system()函数执行了三步操作:
1.fork一个子进程;
2.在子进程中调用exec函数去执行command;
3.在父进程中调用wait去等待子进程结束。
#include<stdlib.h>
int main()
{
system("ls");
return 0;
}
返回值:
1>如果 exec 执行成功,即 command 顺利执行,则返回 command 通过 exit 或 return 的返回值。(注意 :command 顺利执行不代表执行成功,当参数中存在文件时,不论这个文件存不存在,command 都顺利执行)
2>如果exec执行失败,也即command没有顺利执行,比如被信号中断,或者command命令根本不存在, 返回 127
3>如果 command 为 NULL, 则 system 返回非 0 值.
4>对于fork失败,system()函数返回-1。