Shell Commands

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
User avatar
Frosty
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 10
Joined: Sat Feb 21, 2009 5:51 pm
Favorite Gaming Platforms: Xbox 360, Playstation 3
Programming Language of Choice: C++
Location: New York
Contact:

Shell Commands

Post by Frosty »

Okay, I wrote a basic program for shell commands.
Since alot of people were asking me how to do it.
This is a great reference for all you guys wanting to learn how to execute Shell commands in c++

Code: Select all

#include <iostream>
#include <unistd.h>

int
main()
{
int rv = system("ls -l ~/");
std::cout << "result code: " << rv << "\n";
return 0;
}

Here's an example of doing it the hard way.

Code: Select all

#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int
main()
{
int kidstatus, deadpid;

pid_t kidpid = fork();
if (kidpid == -1) {
std::cerr << "fork error " << errno << ", "
<< std::strerror(errno) << "\n";
return 1;
}
if (kidpid == 0) {
// okay, we're the child process. Let's transfer control
// to the ls program. "ls" in both of the spots in the list
// is not a mistake! Only the second argument on are argv.
// note the NULL at the end of the list, you need that.
#if 0
// this version uses the shell.
int rv = execlp("/bin/sh", "/bin/sh", "-c", "ls -l /var/log", NULL);
#else
// this version runs /bin/ls directly.
int rv = execlp("/bin/ls", "/bin/ls", "-l", "/var/log/", NULL);
#endif
// if the execlp is successful we never get here:
if (rv == -1) {
std::cerr << "execlp error " << errno << ", "
<< std::strerror(errno) << "\n";
return 99;
}
return 0;
}
// we only get here if we're the parent process.
deadpid = waitpid(kidpid, &kidstatus, 0);
if (deadpid == -1) {
std::cerr << "waitpid error " << errno << ", "
<< std::strerror(errno) << "\n";
return 1;
}
std::cout << "child result code: " << WEXITSTATUS(kidstatus)
<< "\n";
return 0;
}
User avatar
eatcomics
ES Beta Backer
ES Beta Backer
Posts: 2528
Joined: Sat Mar 08, 2008 7:52 pm
Location: Illinois

Re: Shell Commands

Post by eatcomics »

Sweet, I may be able to use this for my ipod linux development, if I choose to actually attempt it...
Image
Post Reply