1、fork()函数
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int count = 0;
int main1()
{
// 创建子进程
// 返回值:1、在父进程中返回子进程的pid 2、在子进程中,返回0
// 创建成功以后,子进程和父进程的执行顺序是不固定的
pid_t pid = fork();
if (pid > 0) // 父进程
{
printf ("我是父进程, id = %d\n", getpid());
}
else if (0 == pid) // 子进程
{
printf ("我是子进程,id = %d, ppid = %d\n", getpid(), getppid());
}
count++;
printf ("count = %d\n", count);
while (1);
return 0;
}
int main2()
{
fork();
fork();
fork();
while (1);
return 0;
}
int main3()
{
fork();
fork() && fork() || fork();
fork();
while (1);
return 0;
}
int main()
{
int i;
for (i = 0; i<10; i++)
{
pid_t pid = fork();
if (0 == pid)
break;
}
while (1);
return 0;
}
2、exec相关函数
#include <stdio.h>
#include <unistd.h>
int main1(int argc, char **argv)
{
printf ("开始文件复制......\n");
// execl("mycopy", "./mycopy", "1.ppt", "2.ppt", NULL);
execl("/bin/cp", "cp", "1.ppt", "2.ppt", NULL);
printf ("文件复制结束......\n");
return 0;
}
int main2(int argc, char **argv)
{
printf ("开始文件复制......\n");
// 对于非系统命令,要写出完整路径
execlp("/mnt/hgfs/code/171/21/mycopy", "./mycopy", "1.ppt", "2.ppt", NULL);
// 对于系统命令,可以不用谢完整路径,会自动去 path 指定的路径下找命令
// execlp("cp", "cp", "1.ppt", "2.ppt", NULL);
printf ("文件复制结束......\n");
return 0;
}
int main3(int argc, char **argv)
{
printf ("开始文件复制......\n");
char *buf[] = {"./mycopy", "1.ppt", "2.ppt", NULL};
execv("mycopy", buf);
printf ("文件复制结束......\n");
return 0;
}
int main(int argc, char **argv)
{
printf ("开始文件复制......\n");
// system("./mycopy 1.ppt 2.ppt");
system("ls --color=auto");
printf ("文件复制结束......\n");
return 0;
}
3、僵尸进程
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int i;
for (i = 0; i < 10; i++)
{
pid_t pid = fork();
if (0 == pid)
{
//printf ("子进程退出\n");
//exit(0);
break;
}
}
while (1);
return 0;
}
4、守护进程
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
daemon(0, 0);
FILE *fp = fopen("/mnt/hgfs/code/171/21/tmp1", "w");
if (NULL == fp)
{
perror("打开文件失败");
return -1;
}
while (1)
{
fputs("hello world", fp);
fflush(fp);
sleep(1);
}
fclose (fp);
return 0;
}