【发布时间】:2021-07-23 07:03:35
【问题描述】:
我写了以下代码:
void execute() {
std::cout << "smash pid is " << getpid() << std::endl;
}
int main()
{
int pid=fork();
if (pid==0)
{
int fd=open("my_file.txt", O_WRONLY | O_CREAT, 0666); // 3=my_file
dup2(fd,1); // replace output stream
close(fd); //close duplicate access to my_file
execute();
close (1); // close last access to my file
}
else if (pid>0)
{
std::cout << "Hello!" << std::endl;
}
return 0;
}
我的问题是我做事正确吗?主进程还能像往常一样访问终端打印吗?
我尝试添加我正在做的事情的注释,如果有不清楚的地方请告诉我。
版本 2:
int main()
{
int pid=fork();
if (pid==0)
{
close (1);
int fd=open("my_file.txt", O_WRONLY | O_CREAT, 0666); // 3=my_file
execute();
close (1); // close last access to my file
}
else if (pid>0)
{
std::cout << "Hello!" << std::endl;
}
return 0;
}
【问题讨论】:
-
您正在尝试将标准输出重定向到子进程中的文本文件,对吗?版本 1 看起来不错。问:版本 1 是否按您的预期工作?问:版本 2 是否失败?问:你为什么首先这样做?你想在这里展示什么?