Skip to content

Instantly share code, notes, and snippets.

@shonenada
Created October 16, 2013 13:24
Show Gist options
  • Save shonenada/7007664 to your computer and use it in GitHub Desktop.
Save shonenada/7007664 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>
pid_t create_process(void(*ptr) ());
int tprintf(const char* fmt, ...);
void childProcess();
void parentProcess(pid_t pid);
int main(void){
int i = 0, j = 0;
// 父进程输出信息
printf("Hello from Parent Process, PID is %d.\n", getpid());
// 创建第一个子进程
pid_t pid_1 = create_process(childProcess);
if (pid_1 != -1 && pid_1 != 0){
// 父进程执行
parentProcess(pid_1);
// 创建第二个进程
pid_t pid_2 = create_process(childProcess);
if (pid_2 = -1 && pid_2 != 0){
parentProcess(pid_2);
}else if(pid_2 != 0){
tprintf("Everything was gone without error.\n");
}
// 等待子进程执行完毕
waitpid(pid_1, NULL, 0);
waitpid(pid_2, NULL, 0);
}
else if(pid_1 != 0){
tprintf("Everything was gone without error.\n");
}
return 0;
}
// 创建进程函数
pid_t create_process(void(*ptr) ()){
// 创建新进程
pid_t pid;
pid = fork();
if(pid == 0){
// 该进程执行
(*ptr)(); // 调用传入的函数
}
return pid;
}
// 子进程执行函数
void childProcess(){
int i;
sleep(1);
for (i=0; i<5; ++i){
printf("Hello from Child Process %d. %d times\n", getpid(), i+1);
sleep(1);
}
}
// 父进程执行函数
void parentProcess(pid_t pid){
// 传入子进程 id,输出进程信息。
tprintf("Parent forked one child process -- %d.\n", pid);
tprintf("Parent is waiting for children to exit.\n");
tprintf("Child process has exited.\n");
tprintf("Parent had exited.\n");
}
int tprintf(const char* fmt, ...){
va_list args;
struct tm * tstruct;
time_t tsec;
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