注释
- 使用系统调用fork()创建三个子进程;
- 各个子进程显示和输出一些提示信息和自己的进程标识符;
- 父进程显示自己的进程ID和一些提示信息,然后调用waitpid()等待多个子进程结束,并在子进程结束后显示输出提示信息表示程序结束。
代码
#include <iostream>
#include <unistd.h>
#include <cstdarg>
#include <wait.h>
#include "crypto_util.h"
int get_file(const std::string file_name){
size_t get_file_id = 0;
std::cout << hsm::common::get_md5_digest_hex(file_name) << std::endl;
get_file_id = strtol(reinterpret_cast<const char *>(hsm::common::get_md5_digest_hex(file_name).substr(0,7).c_str()), nullptr, 16);
return get_file_id;
}
int tprintf(const char *fmt,...){
va_list args;
struct tm* t_struct;
time_t t_sec;
t_sec = time(nullptr);
t_struct = localtime(&t_sec);
printf("%02d:%02d:%02d:%5d|",t_struct->tm_hour,t_struct->tm_min,t_struct->tm_sec,getpid());
va_start(args,fmt);
return vprintf(fmt,args);
}
int main(void) {
std::cout << "Start!" << std::endl;
printf("Father progress,PID is %d.\n",getpid());
pid_t pid1 = fork();
if(pid1 == 0){
printf("Children progress 1,PID is %d.\n",getpid());
exit(1);
printf("Children progress 1 over.\n");
}
pid_t pid2 = fork();
if(pid2 == 0){
printf("Children progress 2,PID is %d.\n",getpid());
exit(1);
printf("Children progress 1 over.\n");
}
pid_t pid3 = fork();
if(pid3 == 0){
printf("Children progress 3,PID is %d.\n",getpid());
exit(1);
printf("Children progress 1 over.\n");
}
else if (pid1 != -1 ){
tprintf("Parent forked children process-- %d.\n",pid1);
tprintf("Parent is waiting for child to exit.\n");
waitpid(pid1,NULL,0);
waitpid(pid2,NULL,0);
waitpid(pid3,NULL,0);
tprintf("Child Process had exited.\n");
tprintf("Parent had exited.\n");
} else{
tprintf("Everything was done without error.\n");
}
return 0;
}