How do I run an external program?

后端 未结 1 877
南笙
南笙 2021-01-06 14:16

I\'m on Linux mint 12.

I want to run a program usr/share/application/firefox and then pass a string anywhere. I haven\'t found a solution for Linux but

相关标签:
1条回答
  • 2021-01-06 15:09

    This can be done using either system which is the same as calling os.system in Python or fork and execl or popen which is similar to calling subprocess.Popen in Python.

    Some examples are shown below. They should work on Linux or Mac.

    For Windows use _system and _popen instead, using if defined function of the C preprocessor.

    IFDEF Example

    #ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */
    # callto system goes here
    #elif defined _WIN32 /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows   systems */
    # callto _system goes here
    #endif
    

    They are architecture dependent, though the location of the firefox binary may not be on various systems.

    system

    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char **argv)
    {
        system("/usr/share/application/firefox");
        printf("Command done!");
        return 0;
    }
    

    popen

    #include <stdio.h>
    int main(int argc, char **argv))
    {
       FILE *fpipe;
       char *command="/usr/share/application/firefox";
       char line[256];
    
       if ( !(fpipe = (FILE*)popen(command,"r")) )
       {  // If fpipe is NULL
          perror("Problems with pipe");
          exit(1);
       }
    
       while ( fgets( line, sizeof line, fpipe))
       {
         printf("%s", line);
       }
       pclose(fpipe);
       return 0;
    }
    
    0 讨论(0)
提交回复
热议问题