c - 使用 sed 和 execvp 来削减部分粗壮。C
问题描述
我正在使用一个函数来回显一个字符串并将输出重定向到 c 中的 sed 输入。如果我回显一个字符串,如“hello:bye bye”,我需要剪切“:”之前的所有内容。所以我为此构建了一个 fork 和 pipe 的函数,但 sed 无法识别我的正则表达式:
void sender (char * str_ ,char * pipe_ ,char **args_) {
int fd[2];
int pid;
char* cmd1[] = {"echo", str_,NULL};
char* sed[] = {"sed","'[^:]*$'",NULL};
int status;
pid = fork();
if (pid == 0) {
if(pipe(fd) < 0){
exit(100);
}
pid = fork();
if (pid == 0) {
close(fd[0]);
dup2(fd[1], 1);
close(fd[1]);
execvp(cmd1[0], cmd1);
printf("Error in execvp1\n");
}else{
close(fd[1]);
wait(&status);
dup2(fd[0],0);
close(fd[0]);
dup2(1,2);
execvp(sed[0],sed);
printf("Error in execvp2\n");
}
}
else{
close(fd[0]);
close(fd[1]);
wait(&status);
wait(&status);
}
}
由于 sed:expression -e #1, character 1: unknown command: `'' 而读取的每一行的输出都是错误的
解决方案
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
void pipe_exec(int pfd[], char *cmd_args[], int redirect_output)
{
printf("%s, pid %d\n", cmd_args[0], getpid());
if (redirect_output)
dup2(pfd[1], 1);
else
dup2(pfd[0], 0);
close(pfd[0]);
close(pfd[1]);
execvp(cmd_args[0], cmd_args);
printf("Error in execvp\n");
exit(1);
}
void sender(char *str_, char *unused1, char **unused2)
{
int status, pid, fd[2];
char *cmd1[] = { "echo", str_, NULL };
char *sed[] = { "sed", "s/[^:]*://", NULL };
if (pipe(fd) < 0)
exit(100);
pid = fork();
if (pid == 0)
pipe_exec(fd, cmd1, 1);
pid = fork();
if (pid == 0)
pipe_exec(fd, sed, 0);
close(fd[0]);
close(fd[1]);
wait(&status);
wait(&status);
}
int
main(void)
{
sender("hello: bye bye", NULL, NULL);
return (0);
}
推荐阅读
- python - 在 python 中使用 web 抓取 beautifulsoup 提取名称时不匹配
- django - Axios POST 调用不适用于 JWT 令牌,而 GET 调用有效
- django - 无法使用 Django Rest Framework 通过模型表示序列化的 ManyToMany 的所有字段
- javascript - javascript 正则表达式在第一个逗号之前提取文本并删除数字
- javascript - 无法访问 OMDb API
- npm - 从本地 GitLab 迁移到基于云的 GitLab 会导致 npm 测试失败:“TypeError: Cannot read property 'close' of undefined”
- codenameone - 是否可以在其他地方重复使用工具栏溢出菜单?
- r - 用 stringr 提取更大的字符数据体?
- javascript - 如何获得更改输入值的差异?
- python - 字典理解值是列表