Created
October 16, 2013 12:20
-
-
Save shonenada/7006830 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdarg.h> | |
#include <time.h> | |
int tprintf(const char* fmt, ...); | |
int main(void){ | |
int i = 0, j = 0; | |
// 父进程显示自己的进程 ID | |
printf("Hello from Parent Process, PID is %d.\n", getpid()); | |
// 创建子进程 | |
// 当 pid == 0 为真的时候,表示当前为子进程执行时间。 | |
// 当 pid == -1 为真的时候,表示创建子进程出错 | |
// 除上述的情况外,为父进程执行时间。 | |
pid_t pid; | |
pid = fork(); | |
if (pid == 0){ | |
// 子进程执行 | |
// 进程挂起进行 1 秒。 | |
sleep(1); | |
// 循环显示子进程信息 | |
for (i=0; i<3; ++i){ | |
printf("Hello from Child Process %d. %d times\n", getpid(), i+1); | |
sleep(1); | |
} | |
} | |
else if (pid != -1){ | |
// 父进程执行 | |
tprintf("Parent forked one child process -- %d.\n", pid); | |
tprintf("Parent is waiting for chile to exit.\n"); | |
// 等待子进程执行完毕退出 | |
waitpid(pid, NULL, 0); | |
// 输出信息 | |
tprintf("Child process has exited.\n"); | |
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