[英]Fork and Pipe problem - unlimited printing
After launching this code in int main(): 在int main()中启动此代码后:
int p[2];
char *argv[2];
argv[0] = "wc";
argv[1] = "0";
pipe(p);
if(fork() == 0) {
close(0);
dup(p[0]);
close(p[0]);
close(p[1]);
execv("/bin/wc", argv);
} else {
close(p[0]);
write(p[1], "pls work finally jesus\n", 12);
close(p[1]);
}
I end up with unlimited "> > > > > > > > > > > > > (...)" constantly printing in my terminal. 我最终在终端中不断打印无限的“>>>>>>>>>>>>(...)”。 How can i fix that?
我该如何解决?
Per the POSIX execv()
documentation (bolding mine): 根据POSIX
execv()
文档 (正在开发中):
int execv(const char *path, char *const argv[]);
...
...
The argument
argv
is an array of character pointers to null-terminated strings.参数
argv
是指向空终止字符串的字符指针数组。 The application shall ensure that the last member of this array is a null pointer.应用程序应确保此数组的最后一个成员为空指针。 ...
...
This does not meet those conditions: 这不满足那些条件:
char *argv[2];
argv[0] = "wc";
argv[1] = "0";
"0"
is not a "null pointer". "0"
不是“空指针”。 You're assigning the address of a string literal that contains the string "0"
to argv[1]
. 您正在将包含字符串
"0"
的字符串文字的地址分配给argv[1]
。 Since the last member of the array isn't a "null pointer", you're invoking undefined behavior. 由于数组的最后一个成员不是“空指针”,因此您正在调用未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.