c++ - 如何在子进程结束后立即捕获它?
问题描述
我写了一个使用fork的复制函数,以使该函数在后台运行,子进程应该复制文件,而父进程不会等待子进程完成,我的问题是我想当孩子完成复制文件时打印" copying was complete "
按摩,但我不知道如何在孩子进程结束后立即捕捉到蚂蚁帮助?
void copyFunction::execute() {
char *buff = new char[1024]();
int fdRead = open(args[1], O_RDONLY);
if (fdRead == -1) {
perror(" error: open failed");
return;
}
int fdWrite = open(args[2], O_WRONLY | O_TRUNC);
if (fdWrite ==-1) { // if we couldn't open the file then create a new one (not sure if we supposed to this ?)
fdWrite = open(args[2], O_WRONLY | O_CREAT, 0666);
if (fdWrite == -1) {
perror(" error: open failed");
return;
}
}
PID = fork();
if (PID == 0) {
setpgrp();
int count = read(fdRead, buff, 1); /// read from the file fd1 into fd2
while (count != -1) {
if (!count) {
break;
}
if (write(fdWrite, buff, 1) == -1) {
perror(" error: write failed");
return; // not sure if we should return
}
count = read(fdRead, buff, 1);
if (count == -1) {
perror(" error: read failed");
exit(1) ;
}
}
exit(1) ;
} if (PID > 0) {
SmallShell::getInstance().Jobs_List.addJob(SmallShell::getInstance().currentCommand, false);
return;
} else {
perror(" error: fork failed");
}
}
在哪里打电话?
cout << "copying was complete" << endl;
解决方案
使用 wait() 调用。
PID = fork();
if(PID > 0){
wait(NULL);
cout << " copying is complete" << endl;
}
推荐阅读
- c++ - C++ 为什么基类/结构构造函数不能有多个参数可以从派生中隐式调用?
- c - 对从静态库调用的函数的未定义引用
- android - 今天我在android代码中遇到了非常异常的错误
- java - 为什么java从另一个类中获取一个类的旧变量值?
- ruby - 在 shopify 中显示基于 zip、省和国家/地区的运费
- python-2.7 - 使用python获取具有定义长度的子字符串值
- c++ - 如何在不使用重载的情况下将我编写的所有内容组合到一个模板中?
- flutter - 发送带有令牌的 post 方法时获取“此请求的授权已被拒绝”
- google-sheets - 谷歌表格查询 - 不像部分匹配
- sql-server - 自定义任务在 SSIS 工具箱中不可见