Execlp() function in C
×


Execlp() function in C

182

The execlp() function in C is used to replace the current process with a new process specified by the provided command.

It's part of the header file and is commonly used in Unix-based operating systems.

The execlp() function searches for the specified command in the directories listed in the PATH environment variable.

If the command is found, it replaces the current process with the new process.

The new process starts executing from the beginning of the specified command, and arguments can be passed to it.

Syntax execlp() function in C:

int execlp(const char *command, const char *arg0, ... /*, (char *) NULL */);

command: The name of the command to be executed.

arg0: The first argument to the command.

(char *) NULL: A list of NULL-terminated strings representing the command-line arguments, with a final NULL pointer indicating the end of the argument list.

Example:

// program for execlp() in C
#include<stdio.h> 
#include<unistd.h> 

int main() {
    printf("Executing ls command...\n");

    // Execute ls command using execlp
    execlp("ls", "ls", "-l", NULL);

    // If execlp fails, this line will be reached
    perror("execlp");
    return 1; // Exit with error code 1
}	

Output:

Executing ls command...
ls: command not found
execlp: Success

Uses execlp() function in C 

Running external commands or programs from within a C program.

Useful in shell scripting and process management.

Automating tasks that involve executing system commands.

When you run this program, it will execute the ls -l command, listing the contents of the current directory in long format.

If the execlp() function fails for any reason, it will print an error message using perror().

It's important to note that after a successful call to execlp(), the current process is replaced, and the code following the call will not be executed unless the execlp() function fails.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments