Ask Your Question

Revision history [back]

As far as I'm aware, you can't redirect files like that with execl. Here's a complete example with redirection written in C (should also compile in C++, but change NULL to nullptr).

Also be sure to source your ROS environment before you execute this.

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char ** argv)
{
  int pid = fork();
  if (-1 == pid) {
    /* fork failed */
    perror("fork");
    return 1;
  } else if (0 == pid) {
    /* child process */
    FILE * fp = fopen("navstackoutput.txt", "w");
    if (NULL == fp) {
      perror("fopen");
      return 1;
    }
    /* get descriptor for the file */
    int fd = fileno(fp);
    /* redirect stderr to stdout */
    dup2(fd, 1);
    /* redirect stdout (and stderr) to the file */
    dup2(fd, 2);
    close(fd);  /* close redundant fd */
    execlp("roslaunch", "roslaunch", "gazebo_ros", "willowgarage_world.launch", NULL);
    perror("execlp");  /* should never get here */
  } else {
    /* parent process */
    printf("Waitind for pid '%d' to exit...\n", pid);
    int status;
    int ret = waitpid(pid, &status, WUNTRACED);
    if (0 > ret) {
      perror("waitpid");
      return 1;
    }
    printf("Child exited with return code '%d'\n", status);
  }

  return 0;
}

As far as I'm aware, you can't redirect files like that with execl. Here's a complete example with redirection written in C (should also compile in C++, but change NULL to nullptr).

Also be sure to source your ROS environment before you execute this.

#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char ** argv)
{
  int pid = fork();
  if (-1 == pid) {
    /* fork failed */
    perror("fork");
    return 1;
  } else if (0 == pid) {
    /* child process */
    FILE * fp = fopen("navstackoutput.txt", "w");
    if (NULL == fp) {
      perror("fopen");
      return 1;
    }
    /* get descriptor for the file */
    int fd = fileno(fp);
    /* redirect stderr to stdout */
    dup2(fd, 1);
    /* redirect stdout (and stderr) to the file */
    dup2(fd, 2);
    close(fd);  /* close redundant fd */
    execlp("roslaunch", "roslaunch", "gazebo_ros", "willowgarage_world.launch", NULL);
    perror("execlp");  /* should never get here */
  } else {
    /* parent process */
    printf("Waitind printf("Waiting for pid '%d' to exit...\n", pid);
    int status;
    int ret = waitpid(pid, &status, WUNTRACED);
    if (0 > ret) {
      perror("waitpid");
      return 1;
    }
    printf("Child exited with return code '%d'\n", status);
  }

  return 0;
}

I should also note that the process will probably hang until you manually kill it, so you should do a kill -SIGINT [pid] where pid is the number output in the line "Waiting for pid '%d' to exit...".