Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created October 16, 2013 12:19
Show Gist options
  • Save shonenada/7006827 to your computer and use it in GitHub Desktop.
Save shonenada/7006827 to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <stdarg.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int tprintf(const char* fmt, ...);
int main(void){
// 创建子进程
// 当 pid == 0 为真的时候,表示当前为子进程执行时间。
// 当 pid == -1 为真的时候,表示创建子进程出错
// 除上述的情况外,为父进程执行时间。
pid_t pid;
pid = fork();
if (pid == 0){
// 子进程执行
// 进程挂起进行 1 秒。
sleep(1);
// 子进程输出信息
tprintf("Hello from Child Process!\n");
tprintf("I am calling exec.\n");
// 调用外部命令 "/bin/ps -a"
execl("/bin/ps", "-a", NULL);
// execl()(以及 exec() 族函数)函数将会用目标程序进程替换目前正在执行的进程
// 所以后续的语句将不会再被执行。
tprintf("You should never see this b/c the child is already gone.\n");
}
else if (pid != -1){
// 父进程执行
// 父进程显示自己的进程 ID
tprintf("Hello from Parent, pid %d.\n", getpid());
tprintf("Parent forked process %d.\n", pid);
tprintf("Parent is waiting for child to exit.\n");
// 等待子进程执行结束。
waitpid(pid, NULL, 0);
tprintf("Parent had exited.\n");
}
else tprintf("Everything was gone without error.\n");
return 0;
}
int tprintf(const char* fmt, ...){
va_list args;
struct tm * tstruct;
time_t tsec = time(NULL);
tstruct = localtime (&tsec);
printf("%02d:%02d:%02d: %5d|", tstruct->tm_hour, tstruct->tm_min, tstruct->tm_sec, getpid());
va_start(args, fmt);
return vprintf(fmt, args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment