简单的system例子
#include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <stdio.h> int system_test(const char* cmdstring) { pid_t pid; int status; if (cmdstring == NULL) return 1; if ((pid = fork()) < 0) { // error status = -1; } else if (pid == 0) { // son printf("[%s]\n", cmdstring); execl("/bin/sh", "sh", "-c", cmdstring, NULL); } else { // father while(waitpid(pid, &status, 0) < 0) { if (errno != EINTR) { status = -1; break; } } } } int main() { char cmd[100] = {0}; long tstamp = 166451600; snprintf(cmd, 100, "echo \"root: %ld\" > /tmp/time", tstamp * 1000); system_test(cmd); }
关于fork()函数
#include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <pthread.h> int system_test(const char* cmdstring) { pid_t pid; int status; if ((pid = fork()) < 0) { // error status = -1; } else if (pid == 0) { // son printf("son [%d] \n", getpid()); } else { // father printf("father [%d] son [%d]\n", getpid(), pid); while(waitpid(pid, &status, 0) < 0) { if (errno != EINTR) { status = -1; break; } } printf("son exit\n"); } } int main() { char cmd[100] = {0}; system_test(cmd); }
打印:
pc123@ubuntu:~$ gcc maintest.cpp pc123@ubuntu:~$ ./a.out father [15385] son [15386] son [15386] son exit pc123@ubuntu:~$
上面的例子可以看出:
- fork返回值:
=0 : error ,
满足> 0条件:代表是父进程,其中的pid是子进程的进程号
满足< 0条件:代表是子进程。
- waitpid操作
这个是用来给子进程收尸用的,当传入的第一个参数是>0的pid, 代表给进程号为pid的进程收尸。