简体   繁体   English

使用execvp将md5sum重定向到文件?

[英]Redirect md5sum to a file using execvp?

i need to get the checksum of a file using md5sum, inside a C project. 我需要在C项目中使用md5sum获取文件的校验和。

I can't use the openssl library because it isn´t installed, and i can't install it, because it's the university server that i'm working on. 我无法使用openssl库,因为它尚未安装,我也无法安装,因为它是我正在使用的大学服务器。

Also i have some requirements, and i can not use system(), which would be very simple to just: system("md5sum fileName > testFile"); 我也有一些要求,并且我不能使用system(),这只是非常简单:system(“ md5sum fileName> testFile”);

They also don't allow me to use popen(); 他们也不允许我使用popen();

Im trying to make it work using execvp, but it's not actually working, and i don't know if i can actually work. 我正在尝试使用execvp使其工作,但是它实际上没有工作,而且我不知道我是否可以实际工作。

The test file that im actually using is this: 我实际使用的测试文件是这样的:

  int main(){

      char *const args[] = {"md5sum","file"," > ","test", NULL};                                                                                                                                             

      execvp(args[0],args);  

      return 0;
  }

When i open the file "test" nothing is writed there, 当我打开文件“测试”时,那里什么也没写,

Any clue on how to do it, or why it isn't working?? 关于如何执行此操作的任何线索,或为何不起作用?

Thanks in advance. 提前致谢。

> is processed by the shell, it's not an argument to the program that you run with execvp . >由shell处理,它不是您使用execvp运行的程序的参数。

Redirect your process's stdout before calling execvp . 在调用execvp之前,请重定向进程的stdout

int main(){
    char *const args[] = {"md5sum", "file", NULL};  

    int fd = open("test", O_WRONLY, 0777);
    dup2(fd, STDOUT_FILENO);
    close(fd);
    execvp(args[0], args);

    return 0;
}

You are passing > as an argument to the command. 您正在传递>作为命令的参数。 Usually writing command > file works because the shell that you are using parses > as redirection symbol and redirects the standard output of your program to the file ( > is never passed to the command itself). 通常编写command > file之所以有效,是因为您使用的pars >外壳程序将其作为重定向符号并将程序的标准输出重定向到该文件( >从未传递给命令本身)。

What you are trying to is 你想做的是

int main()
{
    const char* args[]={"md5sum","file",0};
    int fd=open("test",O_CREAT|O_WRONLY,S_IRWXU);
    pid_t pid=fork();

    if(!pid)
    {
         dup2(fd,STDOUT_FILENO);
         close(fd);
         execvp(agrs[0],args);
    }
 // ...

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM