-1

我已经execl()在代码中使用过,效果很好。

但这一次,我真的不知道为什么它不起作用。

所以这是不起作用的代码

#include <unistd.h>
#include <stdio.h>

int main()
{
     int i = 896;

     printf("please\n");
     execl("home/ubuntu/server/LC/admin/admin", (char*)i, NULL);
     printf("i have no idea why\n");

     return 0;
}

这是 admin.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
     int mid = argv[0];

     printf("hi from child\n");
     printf("%d\n", mid);
     return 0;
}

当然我把admin.c编译成admin,路径没有错。

>ls
admin admin.c why why.c
>pwd
/home/ubuntu/server/LC/admin
>./admin
hi from child
-1180858374
>./why
please
i have no ida why

有谁知道为什么它不起作用?

4

1 回答 1

0

我的 C 有点生疏,但你的代码犯了很多新手错误。

  1. execl如果成功,将替换当前进程。因此,如果孩子可以成功启动,最后一行(“我不知道为什么”)将不会打印。意思是...

  2. execl失败了,你没有检查它!提示:检查类型转换为char *.

  3. 您在调用中将 anint转换为 a ,然后在您启动子 ( ) 时再次转换。这是 C 语言中的一大禁忌。它允许您自由地误解类型。唯一的警告通常是崩溃。GGC 会警告您。我不知道 AWS 上的编译器。char *execladmin

  4. 检查你的数组的界限!您不知道admin启动了多少参数。argv[0]始终存在,因为它包含程序名称的表示。argv[1]可能没有定义。越界访问数组是一种未定义的行为并且非常危险。

在 C 中启动另一个进程的标准方法是到fork父进程,然后调用exec族中的一个函数来启动另一个进程。

考虑一下这个(我冒昧地发出不同的消息以使它们更清晰)。

父.c

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
    int i = 896;
    char str[15];
    int pid;

    printf("Hello from parent\n");
    sprintf(str, "%d", i); // convert the number into string

    pid = fork();
    if (pid == -1)
    {
        printf("Fork failed\n");
    }
    else if (pid == 0)
    {
        printf("Continue from parent\n");
    }
    else
    {
        // start the child process
        execl("home/ubuntu/server/LC/admin/admin", str, NULL);

        // check if it started properly
        if (errno != 0)
        {
            printf("Error launching child process: %s\n", strerror(errno));
            return 1;
        }
    }

    printf("Goodbye from parent\n");    
    return 0;
}

管理员.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/msg.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    char * mid;

    // argc is always 1 or more
    if (argc >= 2)
        mid = argv[1];
    else
        mid = "<nothing>";

    printf("hello from child\n");
    printf("argc = %d, argv[1] = %s\n", argc, mid);
    return 0;
}
于 2015-06-15T02:39:56.067 回答