简体   繁体   中英

How to display “help” command in linux terminal using C?

I need a little help on simulating a terminal command within a C program. More specifically the "help" command.

Just to clarify what's going on here. I'm working on an assignment to build a C program under the Linux environment that will prompt the user to enter a command (user will type an actual Linux command within the C program), the program will read the user input, and output the result of the command as if you were typing the command in the terminal.

I'm new to working in both Linux and C, but I think I can build the main program. I just want to learn how to run Linux commands within a C program. I researched and have successfully done so with a few commands, such as "clear" and "ls", but I have not been able to get "help" or even "exit" to work.

Here's how I got "ls" to work:

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

    int main(int argc, char *argv[])
    {
       system("ls");

       return 0;
    }

I complied and ran that program and it did exactly what's expected, run the command as if I was typing in the terminal. Now I tried the same thing for "help", but it didn't work in saying the command was "not found." So I searched it up and found that the shell looks in particular directories to execute certain stuff. "Ls" in particular was in /usr/bin. The problem is, I can't seem to find the directory where "help" is stored. Am I in the right direction in looking for a particular directory or is it not possible to run "help" within a C program?

Any help is greatly appreciated!

help is a bash builtin, not a real program you can run.

system(3) uses your system's shell interpreter ( /bin/sh ) to run commands, which happens to have no help builtin on your system.

Use

system("bash -c help");

instead of just "help". It seems that your default shell isn't bash but something else. "bash -c" simply specifies a command specifically to bash (-c option means "command"). You can check this via command line by looking at where /bin/sh is pointing.

ls -l /bin/sh

should give something to the tune of

lrwxrwxrwx 1 root root 4 Sep  9 19:30 /bin/sh -> bash*

or something else

As system(3) doc says, it uses /bin/sh for executing your command line. /bin/sh is not the same as /bin/bash anyway. Even if you have only bash(1) in your system, when you run it as sh , it behaves as if you where using plain sh (runs in compatibility mode), so no help command available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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