Tag Archive: C


Changing process name

A simple trick to change a process name in C programming is to do it:

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

int main(int argc, char **argv) {
    int st = 0;
    int pid = fork();

    /* copy new name to child process */
    if(pid == 0) {
        printf("Check my pid: %d\n", getpid());
        strcpy(argv[0], "new_name");
        sleep(20);
        exit(0);
    }

    wait(&st);
    return 0;
}

To see it in action, firstly, compile the program:

gcc -Wall -o test test.c

Now, execute it in background mode:

./test &

Then, check the name of the process through the given pid:

ps -auxww | grep pid

Yeah!!! The key is argv[0] !!! ;)

You can include arguments too, just do it:

strcpy(argv[0],"newprocess -a -x -y");

Now, use your imagination… =]

Listing Shared Memory Segments in C

In this week I had to write a little code to remove all IPC Shared Memory segments that were created by one process.

I had already done it on Linux and *BSD systems, but never on (Open)Solaris. Then, I tried to search (googling) some method to do it but without successful.

Linux and *BSD’s have a syscall named sysctl() to interface it, but sunos kernel has not.

Well, after some minutes breaking my brain, I discover a syscall easiest to use than sysctl…look the code below:

#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
void show_shm (void)
{
  int i;
  int     *buf;
  uint_t  nids;
  uint_t  pnids;
  for (;;)
  {
    if (shmids(buf, nids, &pnids) != 0)
      exit(1);
    if (pnids <= nids)
      break;
    buf = realloc(buf, (nids = pnids) * sizeof (int));
  }
  for (i = 0; i < pnids; i++)
    printf ("%dn", buf[i]);
}

link2_os_blk_125
Follow

Get every new post delivered to your Inbox.