我试图重新实现system()库函数。但是,如果我通过ps或ls命令作为主要参数传递参数,则不会得到输出。谢谢。
原始代码:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<error.h>
#define buf_size 512
int main(int argc, char *argv[])
{
pid_t pid;
char *buf[buf_size];
int ret = 0;
char ch;
int i = 0;
int j = 0;
if (argc != 2)
error(1, 0, "Too many of less number of arguments\n");
for (i = 1; i < argc; i++) {
*(buf + j) = argv[i];
j++;
}
buf[j] = '\0';
pid = fork();
if (pid == -1) {
error(1, 0, "error in creating the sub-process\n");
} else if (pid == 0) {
execv("bin/sh", buf);
} else {
wait(NULL);
}
}
在阅读了这篇文章中的一些评论后编辑了代码:
int main(int argc, char *argv[])
{
pid_t pid;
int ret;
if (argc != 2)
error(1, 0, "Too many of less number of arguments\n");
pid = fork();
if (pid == -1) {
error(1, 0, "error in creating the sub-process\n");
} else if (pid == 0) {
ret = execv("/bin/sh", argv);
if (ret == -1)
error(1, 0, "error in execv() system call\n");
} else {
wait(NULL);
}
}
答案 0 :(得分:1)
您距离解决方案不远。
您错过的主要事情是应该启动/bin/sh -c ls
而不是bin/sh ls
更正:
buf[j] = "\0";
,而是增加了for循环的大小(注意i<= argc
)/bin/sh
(忘记领先的/
)sh
和-c
添加到sh
选项中。 (请参见man execv)#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<error.h>
int main(int argc, char *argv[])
{
pid_t pid;
char * buf[4];
if (argc != 2)
error(1, 0, "Too many of less number of arguments\n");
buf[0] = "sh";
buf[1] = "-c";
buf[2] = argv[1];
buf[3] = NULL;
pid = fork();
if (pid == -1) {
error(1, 0, "error in creating the sub-process\n");
} else if (pid == 0) {
execv("/bin/sh", buf);
perror("execv");
} else {
wait(NULL);
}
}