Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

10.4.4 wordexp Example

Here is an example of using wordexp to expand several strings and use the results to run a shell command. It also shows the use of WRDE_APPEND to concatenate the expansions and of wordfree to free the space allocated by wordexp.

     int
     expand_and_execute (const char *program, const char *options)
     {
       wordexp_t result;
       pid_t pid
       int status, i;
     
       /* Expand the string for the program to run.  */
       switch (wordexp (program, &result, 0))
         {
         case 0:			/* Successful.  */
           break;
         case WRDE_NOSPACE:
           /* If the error was WRDE_NOSPACE,
              then perhaps part of the result was allocated.  */
           wordfree (&result);
         default:                    /* Some other error.  */
           return -1;
         }
     
       /* Expand the strings specified for the arguments.  */
       for (i = 0; args[i]; i++)
         {
           if (wordexp (options, &result, WRDE_APPEND))
             {
               wordfree (&result);
               return -1;
             }
         }
     
       pid = fork ();
       if (pid == 0)
         {
           /* This is the child process.  Execute the command. */
           execv (result.we_wordv[0], result.we_wordv);
           exit (EXIT_FAILURE);
         }
       else if (pid < 0)
         /* The fork failed.  Report failure.  */
         status = -1;
       else
         /* This is the parent process.  Wait for the child to complete.  */
         if (waitpid (pid, &status, 0) != pid)
           status = -1;
     
       wordfree (&result);
       return status;
     }

 
 
  Published under the terms of the GNU General Public License Design by Interspire