当我调用 execve 时,我收到一个错误,我很困惑为什么当我将 char 数组传递给它时,它不接受我的完整输入并认为它的参数太少。该程序旨在将文件名作为输入,然后将它们排序到名为 SORTED 的目录中。我知道 execve 需要 3 个参数,但是我的调用错了吗?
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main( int argc, char **argv ){
//arguments
int i, status, finish = 1;
pid_t *childPID;
char buffer[256];
//checks to make sure there is arguments
if ( argc < 2 ) {
sprintf( buffer, "No arguments were given.\n" );
write( 2, buffer, strlen( buffer ) );
return (-1);
}
//uses mkdir to check if directory is there
//if it is not, makes it with 0777 permissions
//if it exists, it prints out error message saying that
//any other error happens, it uses perror to print out the error
if(mkdir( "./SORTED", S_IRWXU ) == 0) {
sprintf( buffer, "Creating SORTED folder with 0700 Permissions.\n" );
write( 1, buffer, strlen( buffer ) );
}
else if (errno == EEXIST) {
sprintf( buffer, "SORTED folder already exists.\n" );
write( 2, buffer, strlen( buffer ) );
}
else
perror( "mkdir" );
childPID = (pid_t*)malloc(sizeof(pid_t)*(argc));
//for each argument, forks a new child from parent
//calls execve, prints error if there is one
//and then sleeps for 20 seconds before exiting
for ( i = 1; i < argc; i++ ) {
char output[256];
sprintf( output, "SORTED/%s", argv[i] );
char *newARGV[] = { "sort", "-o", output, argv[i], NULL };
if ( childPID[i] = fork() == 0 ) {
execve( "/usr/bin/sort", newARGV);
perror( "execve" );
exit( 0 );
}
}
//Goes through each argument, waits on the child PID
//Prints if the sort was successful, and if not, prints error code
for ( i = 1; i < argc; i++ ) {
waitpid( childPID[i], &status, 0 );
if ( status == 0 )
sprintf( buffer, "%s : success (%d)\n", argv[i], status );
else {
finish = 0;
sprintf( buffer, "%s : fail (%d)\n", argv[i], status );
}
write( 1, buffer, strlen( buffer ) );
}
//Prints the all done if there was no errors
//informs you if there were errors
if ( finish == 1 )
sprintf( buffer, "All Done.\n" );
else
sprintf( buffer, "All Done. Error was encountered.\n" );
write( 1, buffer, strlen( buffer ) );
free(childPID);
return 0;
}
完整的错误是:
error: too few arguments to function ‘execve’
execve( "/usr/bin/sort", newARGV);
最佳答案
execve
函数需要三个参数,但您要传递两个参数。因此出现错误消息。
您似乎认为将数组传递给函数意味着数组的每个元素都成为函数的参数,但事实并非如此。
该函数声明如下:
int execve(const char *filename, char *const argv[], char *const envp[]);
第一个参数是要运行的命令,第二个是参数数组,第三个是环境变量数组。如果您对传递环境变量不感兴趣,请使用没有第三个参数的 execv
。
关于对 execve 的调用参数太少,但应该接收全部参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56483866/