如何使用execvp() [英] How to use execvp()

查看:256
本文介绍了如何使用execvp()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户将读取一行,并且我将保留第一个单词作为execvp的命令.

The user will read a line and i will retain the first word as a command for execvp.

让我们说他将键入 "cat file.txt" .命令将是cat.但是我不确定如何使用此execvp(),我阅读了一些教程,但仍然没有得到它.

Lets say he will type "cat file.txt" ... command will be cat . But i am not sure how to use this execvp(), i read some tutorials but still didn't get it.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *buf;
    char command[32];
    char name[32];
    char *pointer;
    char line[80];
    printf(">");

    while((buf = readline(""))!=NULL){   
        if (strcmp(buf,"exit")==0)
        break;

        if(buf[0]!=NULL)
        add_history(buf);

        pointer = strtok(buf, " ");
        if(pointer != NULL){
            strcpy(command, pointer);
        }

        pid_t pid;

        int  status;

        if ((pid = fork()) < 0) {     
            printf("*** ERROR: forking child process failed\n");
            exit(1);
        }
        else if (pid == 0) {          
            if (execvp(command, buf) < 0) {     
                printf("*** ERROR: exec failed\n");
                exit(1);
            }
        }
        else                                  
        while (wait(&status) != pid)       
            ;
        free(buf);
        printf(">");
    }///end While
    return 0;
}

推荐答案

第一个参数是您要执行的文件,第二个参数是一个以null终止的字符串的数组,这些字符串代表指定文件的适当参数在手册页中.

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

例如:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

这篇关于如何使用execvp()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆