Skip to content

Instantly share code, notes, and snippets.

@kisom
Last active September 13, 2015 08:04
Show Gist options
  • Save kisom/ca15b2333eb7cda78598 to your computer and use it in GitHub Desktop.
Save kisom/ca15b2333eb7cda78598 to your computer and use it in GitHub Desktop.
cd
Written as a demo of how a shell would implement this, and why it needs
to be a shell builtin.
This won't actually work as a standalone program; chdir(3) only changes
the directory of the current process. As soon as the program exits, it
returns control to the parent process (the shell). If this is executed
as a shell builtin, the shell process's working directory is changed.
/*
* Copyright (c) 2015 Kyle Isom <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <sys/types.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
int ret = -1;
char *newdir = NULL;
struct passwd *pw = NULL;
switch (argc) {
case 1:
newdir = getenv("HOME");
if (NULL != newdir) {
break;
}
pw = getpwuid(getuid());
if (NULL == pw) {
fprintf(stderr, "cd: cannot find home\n");
exit(1);
}
newdir = pw->pw_dir;
if (NULL == newdir) {
fprintf(stderr, "cd: HOME not set\n");
exit(1);
}
break;
case 2:
newdir = argv[1];
break;
default:
fprintf(stderr, "cd: cannot chdir to multiple paths\n");
fprintf(stderr,
" (did you mean to enclose the path in quotes?)\n");
exit(1);
}
ret = chdir(newdir);
if (-1 == ret) {
perror("cd");
exit(1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment