The function execl in linux has been unable to be called successfully, how to pass parameters correctly?

1. In the linux environment, call execl:

if((pid=fork())<0){
            printf("fork error\n");
        }else if(pid==0){  /*child*/
            if(execl("/sbin/ifconfig","ifconfig","eth0","hw","ether",eth0_num,NULL)<0){
                exit(1);
            }else{
                exit(0);        
            }    
}

2. Where the eth0_num variable is returned by another function call and is a pointer:

:int read_data(int addr,char* data,int len)
:read_data(4, eth0_num,6);/*46eth0_num*/

3. But run-time returns are wrong:

ifconfig: invalid hw-addr 

4. The value I printed for eth0_num is: 0x7e8b8bf4

*eth0_num,*(eth0_num+1),*(eth0_num+2): 00  90  8f
The

value is right, but it never works. I have tried another way
to copy char * eth0_num= "1eed19271ab3" directly; and then call execl, without using the parameters of calling read_data from the function, you can ifconfig successfully

5. Give me some advice on how to pass variable parameters, because I need to read the value back from somewhere else

Apr.02,2021

The argument to

execl () is of type char* . You should convert 6 bytes of the Nic address to a string.

for example, the 6 bytes you read is 00 01 02 03 04 05 , which should be converted to "00 strong 01hand 02purl 03purl 04REV 05" .

reference code

-sharpinclude <errno.h>
-sharpinclude <stdio.h>
-sharpinclude <stdlib.h>
-sharpinclude <string.h>
-sharpinclude <sys/types.h>
-sharpinclude <unistd.h>

void read_data(char* data)
{
    //  00 01 02 03 04 05
    unsigned char source[6] = { 0, 1, 2, 3, 4, 5 };
    memcpy(data, source, 6);
}

int main()
{
    pid_t pid;
    char macBin[6];  // :00 01 02 03 04 05 06
    char macHex[18];  // 16: "00:01:02:03:04:05"

    read_data(macBin);
    //  6  16 
    snprintf(macHex, sizeof(macHex),
            "%02X:%02X:%02X:%02X:%02X:%02X",
            macBin[0],
            macBin[1],
            macBin[2],
            macBin[3],
            macBin[4],
            macBin[5]);

    if ((pid = fork()) == -1) {
        perror(NULL);
    } else if (pid == 0) {
        execl("/usr/bin/ip", "ip", "link", "set", "eth0", "address", macHex, NULL);
        perror(NULL);
    }
}

by the way, use the ip tool instead of ifconfig .

Menu