所以这应该做的是fork,让子进程获取文件的文本,然后让父进程修改该文本并将其写入新文件。我有各种各样的怪异现象。整个代码大致是这样的。
#include <iostream>
#include <termios.h>
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
using namespace std;
int parentPID;
int main(int argc, char* argv[]){
parentPID = getpid();
int pipey[2];
int worked = pipe(pipey);
if( worked == - 1){
cout << "Oops. Didn't make a pipe.";
}
//cout << "About to fork!!!";
fork();
if(getpid() != parentPID){//Only run in the child process
char* argvec1[3] = {"cat", "colorfile.txt", (char*)0};
dup2(pipey[1], 1);
execv("/bin/cat", argvec1);
}
else{//Only run in the parent process.
int someInt;
cout << "In the parent process";
pid_t status = wait(&someInt);
dup2(pipey[0], 0);
creat("newfile.txt", 0777);
chmod("newfile.txt", 0777);
int targetFile = open("newfile.txt", O_WRONLY);
if(targetFile == -1){
cout << "\nOops, couldn't open targetFile, ";
perror("because ");
}
else{
cout << "\nOpened target file.";
}
dup2(targetFile, 1);
//char* argvec2[] = {"sed", "-e", "s/color/colour/g", (char*)0};
//execv("/bin/sed", argvec2);
cout << "something went terribly wrong";
}
}
特别麻烦的是三件事,第一,这个代码片段......
creat("newfile.txt", 0777);
chmod("newfile.txt", 0777);
int targetFile = open("newfile.txt", O_WRONLY);
if(targetFile == -1){
cout << "\nOops, couldn't open targetFile, ";
perror("because ");
}
else{
cout << "\nOpened target file.";
}
dup2(targetFile, 1);
...不将“打开的目标文件”写入标准输出。相反,它将它放在 newfile.txt 中,所以 dup2 正在更改出现在它之前的输出命令的输出?...如果我注释掉 dup2,到最后,它不会发生,这绝对是特定的 dup2打电话让它发生。
其次,这个代码片段......
creat("newfile.txt", 0777);
chmod("newfile.txt", 0777);
int targetFile = open("newfile.txt", O_WRONLY);
if(targetFile == -1){
cout << "\nOops, couldn't open targetFile, ";
perror("because ");
}
else{
cout << "\nOpened target file.";
}
//dup2(targetFile, 1);
char* argvec2[] = {"sed", "-e", "s/color/colour/g", (char*)0};
execv("/bin/sed", argvec2);
cout << "something went terribly wrong";
...根本不输出任何关于打开文件的成功/失败。它确实打印出原始文件的内容,并进行了适当的修改,但不会终止。它只是永远存在,直到我使用 ctrl-C 来终止当前进程。不显示最终结果。
最后,这...
creat("newfile.txt", 0777);
chmod("newfile.txt", 0777);
int targetFile = open("newfile.txt", O_WRONLY);
if(targetFile == -1){
cout << "\nOops, couldn't open targetFile, ";
perror("because ");
}
else{
cout << "\nOpened target file.";
}
dup2(targetFile, 1);
char* argvec2[] = {"sed", "-e", "s/color/colour/g", (char*)0};
execv("/bin/sed", argvec2);
cout << "something went terribly wrong";
...没有给我任何输出,无论是标准输出还是 newfile.txt。
感觉这些系统调用中的一些只是按照他们感觉的任何顺序执行,半独立于我编写它们的顺序,因此几乎不可能对它们做任何事情。