Skip to content

Instantly share code, notes, and snippets.

@samthor
Created June 13, 2017 14:05
Show Gist options
  • Save samthor/22ffb5cdafb82362d831e3f837b280e9 to your computer and use it in GitHub Desktop.
Save samthor/22ffb5cdafb82362d831e3f837b280e9 to your computer and use it in GitHub Desktop.
proc_getcwd, get the working dir of arbitrary process (BSD/macOS)
/*
* Copyright 2008 Sam Thorogood. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <libproc.h>
#include <string.h>
/**
* proc_getcwd -- get the working directory of an arbitrary process (BSD)
*
* This function copies the absolute pathname of the current working directory
* into the pointer `ptr`, allocating if it is not passed. This buffer (if
* pre-allocated) should be MAXPATHLEN bytes long.
*
* Note that this will fail if a program does not have enough rights to access
* this information. Typically this means the target must have the same
* effective UID, or the program calling this function must be root.
*
*/
char *proc_getcwd( int pid, char *ptr ) {
struct proc_vnodepathinfo vpi;
/* grab proc info via bsd call */
if( 0 >= proc_pidinfo( pid, PROC_PIDVNODEPATHINFO, 0, &vpi, sizeof( vpi ) ) ) {
return NULL;
}
/* allocate space if required */
if( !ptr ) {
if( !( ptr = ( char * ) malloc( MAXPATHLEN ) ) ) {
errno = ENOMEM;
return NULL;
}
}
/* copy data into output buffer, return */
strcpy( ptr, vpi.pvi_cdir.vip_path );
return ptr;
}
int main( int argc, char **argv ) {
int i, pid;
char *buf;
for( i = 1; i < argc; ++i ) {
pid = atoi( argv[i] );
printf( "%d:\n", pid );
buf = proc_getcwd( pid, NULL );
if( !buf ) {
fprintf( stderr, "can't get cwd of proc %d (%s)\n", pid, strerror( errno ) );
exit( 1 );
}
printf( "%s\n", buf );
free( buf );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment