将Execl命令的结果(是目录列表)输送到父进程
piping the result of execl command, which is directory list, to parent process?
我正在对Linux中的过程管理进行一些练习,以及如何使用孩子和父母之间的系统呼叫和通信。我需要实现一个管道以获取子流程提供的字符串,该流程是字符串的目录列表,并将其传递到父进程以计数该字符串中的行数,并通过执行此操作来查找该目录中的文件数量。我遇到的问题在这里:
错误:初始化器无法确定" dirfilelist"的大小 char dirfilelist [] = read(隧道[0],buf,max_buf)
我的代码也下面是:
#define die(e) do { fprintf(stderr, "%sn", e); exit(EXIT_FAILURE); } while (0);
#define MAX_BUF 2024
int main()
{
const char *path = (char *)"/"; /* Root path */
const char *childCommand = (char *)"ls |"; /* Command to be executed by the child process */
const char *parentCommand = (char *)"wc -l"; /* Command to be executed by the parent process */
int i = 0; /* A simple loop counter :) */
int counter = 0; /* Counts the number of lines in the string provided in the child process */
int dirFileNum; /* Keeps the list of files in the directory */
int tunnel[2]; /* Defining an array of integer to let the child process store a number and parent process to pick that number */
pid_t pID = fork();
char buf[MAX_BUF]; /* Fork from the main process */
if (pipe(tunnel) == -1) /* Pipe from the parent to the child */
die("pipe died.");
if(pID == -1) /* Check if the fork result is valid */
{
die("fork died.");
}
else if(pID == 0) /* Check if we are in the child process */
{
dup2 (tunnel[1], STDOUT_FILENO); /* Redirect standard output */
close(tunnel[0]);
close(tunnel[1]);
execl(childCommand, path); /* Execute the child command */
die("execl died.");
}
else /* When we are still in the main process */
{
close(tunnel[1]);
char dirFileList[] = read(tunnel[0],buf,MAX_BUF); /* Read the list of directories provided by the child process */
for(i;i<strlen(dirFileList);i++) /* Find the number of lines in the list provided by the child process */
if(dirFileList[i] == 'n')
counter++;
printf("Root contains %d files.", counter); /* Print the result */
wait(NULL); /* Wait until the job is done by the child process */
}
return 0;
}
如果您向我们显示了整个错误消息,我们会看到它指的是:
char dirFileList[] = read(tunnel[0],buf,MAX_BUF);
您不能像这样声明不确定的数组。如果您阅读了read(2)
的人页面,您会发现返回值为
成功,字节的数量读取...
错误,-1
...
所以您想要
之类的东西int bytes_read = read(...);
if (bytes_read < 0) {
perror("read");
exit(1);
}
一些其他评论(您没有要求,但可能是有启发性的):
不要将字符串文字投入到char*
,尤其是当您分配给const char*
变量时。
,而不是仅仅在错误时打印固定的消息,而是在使用perror()
设置errno
的呼叫后可以更有用的信息,请参见上面的示例。
die()
可以作为函数实现,这将使调试和正确使用更容易。
相关文章:
- boost::进程间消息队列引发错误
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 复制列表初始化的隐式转换的等级是多少
- LNK2038、MSVS2017 MAGMA的原因列表
- 是否有任何 C 函数或 API 来获取当前登录用户下运行的进程列表
- 使用C 获取Linux进程列表和状态
- 将Execl命令的结果(是目录列表)输送到父进程
- 如何在列表框窗口进程中捕获VK_ESCAPE
- reg.exe在由WinExec()执行后仍保留在进程列表中
- 如何获取特定进程 (Windows 7) 使用的所有 API 的列表
- 如何从win32进程中获取线程句柄列表
- 如何获取绑定到我正在运行的控制台窗口的进程列表,这些进程也可以在 Windows 2000 中工作?
- C++ 分叉子,向子进程询问进程列表,在 Linux 中杀死一个进程
- 参数列表中带有未包装管道符号|的进程