【问题标题】:How to start process on Linux OS in C, C++如何用 C、C++ 在 Linux 操作系统上启动进程
【发布时间】:2015-06-15 16:55:26
【问题描述】:

我有无线 USB 适配器,我使用“pstree”命令监控所有进程。
当我将 USB 适配器插入我的 Linux 操作系统时,我看到带有“pstree”命令的新进程“wpa_supplicant”。

我使用 C/C++ 语言。我知道 Linux 操作系统将使用“NetworkManager”守护进程来监控网络(eth、蓝牙、wifi 等),但我不知道如何启动“wpa_supplicant”?我可以使用 dbus 或 systemd 吗?

谢谢 丁字裤LT

【问题讨论】:

  • 您是否真的尝试过 dbus 或 systemd 以查看它们是否有效?
  • 你真正想要实现什么?无线网络可用时立即开始连接?

标签: c++ linux usb


【解决方案1】:

使用 fork() 系统调用,它将创建一个子进程,或者如果您想通过 C 代码运行可执行文件,则使用 exec() 库函数并指定可执行文件的路径。

代码如下:

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

int main() {
pid_t pid,p;
int i,status;
printf("Parent process starts with PID = %d it's Parent ID %d\n",(int)getpid(),(int)getppid());

if((pid = fork())==-1) {
    fprintf(stderr,"FORK FAILED\n");
    return -1;
}
if(pid == 0 ) {
    printf("Child process starts with PID = %d\n",(int)getpid());
    for(i = 0 ; i < 5; i++) {
        printf("Child prints [%d]\n",i);
        sleep(2);
    }
    _exit(0);
    //exit(0);
}
else {
    p  = wait(&status);
    printf("Parent resumes execution, took control from the child %d \n",(int)p);
    //printf("Return status of the child is %d\n",status);
    for(i = 0; i< 5 ; i++) {
        sleep(2);
        printf("Parent prints [%d]\n",i);
        //sleep(2);
    }
    _exit(0);
}
return 0;

}

【讨论】:

    【解决方案2】:

    标准的 UNIX 方法是使用 fork(2) 后跟 exec(3) 调用(它们有一个完整的家族——选择最适合您需要的那个)。

    使用示例

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    int main(int argc, char **argv)
    {
      pid_t     pid;
    
      printf("before fork\n");   
      if ((pid = fork()) < 0) {
    
        //It may fail -- super rare
        perror("Fork failed");
    
      } else if (pid > 0) {
        //If it returns a positive number, you're in the parent process and pid holds the pid of the child
    
        printf("Mah kid's pid is %d\n", pid);
        printf("Mine's %d\n", getpid());
    
      } else {
        //If it returns zero, you're in the child process
    
        //you can do some preparatory work here (e.g., close filedescriptors)
    
        printf("I'm the child and my pid is %d\n", getpid());
    
        //exec will replace the process image with that of echo (wherever in the PATH environment variable it is be found (using the execlP version here)
        execlp("echo", "echo", "hello world from echo; I'm now the child because I've replaced the original child because it called an exec function", (char*)NULL);
    
        printf("This won't run because now we're running the process image of the echo binary. Not this.");
      }
    
      return EXIT_SUCCESS;
    }
    

    【讨论】:

    • fork() 或 exec 将创建子进程,但我看到 wpa_supplicant 是父进程。我会再次检查 fork 和 exec
    • 我添加了一个注释示例。希望这会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 2013-02-26
    • 1970-01-01
    • 2018-09-19
    相关资源
    最近更新 更多