草庐IT

C++ Fork child,向 child 询问进程列表,在 Linux 中终止进程

coder 2023-06-20 原文

我正在尝试创建一个子进程,向子进程发送命令“LISTALL”。然后子进程应向系统发出命令 ps 并将该列表返回给父进程。然后父进程应该选择一个进程并杀死它。这是我目前所拥有的,但我无法让它运行。

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

char* getlistOfProcesses(const char* cmd) 
{
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return (char*)"ERROR";
    char buffer[128];
    char *result = new char[1024];
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
            strcat(result, buffer);
    }
    pclose(pipe);
    return result;
}

int spawnGEdit()
{
    pid_t gPid = fork();
    if(gPid == 0)
    {
        execl("gedit", "gedit", NULL);
        exit(-1);
    }
    else
    {
    }
    return 0;
}

int main(int argc, char **argv)
{   
    int P2C[2];
    int C2P[2];
    pipe(P2C);
    pipe(C2P);
    pid_t cPid = fork();
    char cmd[50];
    char* listOfProcesses = new char[1024];
    spawnGEdit();

    if (cPid == 0)
    {
        close(P2C[1]); 
        close(C2P[0]); 
        read(P2C[0], cmd, 10);
        if(strcmp(cmd,"LISTALL") == 0)
        {
            write(C2P[1], getlistOfProcesses("ps"), 1024);
            close(P2C[0]);
            close(C2P[1]);
        }
    }
    else if (cPid > 0)
    {
        close(C2P[1]); 
        close(P2C[0]); 
        write(P2C[1], "LISTALL", 10);
        wait(NULL);
        read(C2P[0], listOfProcesses,1024);
        printf("%s",listOfProcesses); 
        //TODO
        //get user input of a PID
        //kill the PID
        close(C2P[0]);
        close(P2C[1]);
    }
    else
    {
        // fork failed
        printf("Forking failed!\n");
        exit(1);
    }
    return 0;
}

这些是我在尝试编译它时遇到的错误:

/tmp/cciTPIOZ.o: In function `getlistOfProcesses(char const*)':
test.cpp:(.text+0x53): undefined reference to `operator new[](unsigned long)'
/tmp/cciTPIOZ.o: In function `main':
test.cpp:(.text+0x166): undefined reference to `operator new[](unsigned long)'
/tmp/cciTPIOZ.o: In function `__static_initialization_and_destruction_0(int, int)':
test.cpp:(.text+0x2c0): undefined reference to `std::ios_base::Init::Init()'
test.cpp:(.text+0x2cf): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status

我正在编译:

cc test.cpp -o test

最佳答案

Compilation Errors occurred on line number:9,53,64 可以使用这些解决:

第 9 行:FILE* pipe = popen(cmd.data(), "r");

第 53 行:write(C2P[1], getlistOfProcesses("ps").data(), 1024);

第 64 行:printf("%s",listOfProcesses.data());

原因:这些 popen、write、printf 需要 char* 作为它们的参数,但您传递给它们的是 std::string。您必须改用 std::string.data() 函数,因为它返回指向由 std::string 对象表示的字符数组的指针。

对于第 63 行的错误,请参阅 this .

PS:- 对于您的相关编辑:

第 10 行:if (!pipe) return (char*)"ERROR";

第 12 行:char *result = new char[1024];

第 53 行:(第 7 行的更改)char* getlistOfProcesses(const char* cmd)

一点建议:在读取 listOfProcessesexit(0); 之前在父进程中使用 wait(NULL);子进程。

工作代码:

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

char* getlistOfProcesses(const char* cmd) 
{
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return (char*)"ERROR";
    char buffer[128];
    char *result = new char[1024];
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
            strcat(result, buffer);
    }
    pclose(pipe);
    return result;
}

int spawnGEdit()
{
    pid_t gPid = fork();
    if(gPid == 0)
    {
        execl("gedit", "gedit", NULL);
        exit(-1);
    }
    else
    {
    }
    return 0;
}

int main(int argc, char **argv)
{   
    int P2C[2];
    int C2P[2];
    pipe(P2C);
    pipe(C2P);
    pid_t cPid = fork();
    char cmd[50];
    char* listOfProcesses = new char[1024];
    spawnGEdit();

    if (cPid == 0)
    {
        close(P2C[1]); 
        close(C2P[0]); 
        read(P2C[0], cmd, 10);
        if(strcmp(cmd,"LISTALL") == 0)
        {
            write(C2P[1], getlistOfProcesses("ps"), 1024);
            close(P2C[0]);
            close(C2P[1]);
        }
        exit(0);
    }
    else if (cPid > 0)
    {
        close(C2P[1]); 
        close(P2C[0]); 
        write(P2C[1], "LISTALL", 10);
        wait(NULL);
        read(C2P[0], listOfProcesses,1024);
        printf("%s",listOfProcesses); 
        //TODO
        //get user input of a PID
        //kill the PID
        close(C2P[0]);
        close(P2C[1]);
    }
    else
    {
        // fork failed
        printf("Forking failed!\n");
        exit(1);
    }
    return 0;
}

关于C++ Fork child,向 child 询问进程列表,在 Linux 中终止进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825694/

有关C++ Fork child,向 child 询问进程列表,在 Linux 中终止进程的更多相关文章

  1. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  4. ruby - RVM 使用列表[0] - 2

    是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论

  5. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  6. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  7. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

  8. ruby - 无法在 Ruby 中将 ffmpeg 作为子进程运行 - 2

    我正在尝试使用以下代码通过将ffmpeg实用程序作为子进程运行并获取其输出并解析它来确定视频分辨率:IO.popen'ffmpeg-i'+path_to_filedo|ffmpegIO|#myparsegoeshereend...但是ffmpeg输出仍然连接到标准输出并且ffmepgIO.readlines是空的。ffmpeg实用程序是否需要一些特殊处理?或者还有其他方法可以获得ffmpeg输出吗?我在WinXP和FedoraLinux下测试了这段代码-结果是一样的。 最佳答案 要跟进mouviciel的评论,您需要使用类似pope

  9. Ruby 守护进程导致 ActiveRecord 记录器 IOError - 2

    我目前正在用Ruby编写一个项目,它使用ActiveRecordgem进行数据库交互,我正在尝试使用ActiveRecord::Base.logger记录所有数据库事件具有以下代码的属性ActiveRecord::Base.logger=Logger.new(File.open('logs/database.log','a'))这适用于迁移等(出于某种原因似乎需要启用日志记录,因为它在禁用时会出现NilClass错误)但是当我尝试运行包含调用ActiveRecord对象的线程守护程序的项目时脚本失败并出现以下错误/System/Library/Frameworks/Ruby.frame

  10. ruby - 在 ruby​​ 中生成一个进程,捕获 stdout,stderr,获取退出状态 - 2

    我想从ruby​​rake脚本运行一个可执行文件,比如foo.exe我希望将foo.exe的STDOUT和STDERR输出直接写入我正在运行rake任务的控制台.当进程完成时,我想将退出代码捕获到一个变量中。我如何实现这一目标?我一直在玩backticks、process.spawn、system但我无法获得我想要的所有行为,只有部分更新:我在Windows上,在标准命令提示符下,而不是cygwin 最佳答案 system获取您想要的STDOUT行为。它还返回true作为零退出代码,这可能很有用。$?填充了有关最后一次system调

随机推荐