diff --git a/src/api.c b/src/api.c
index a98e829..d19abdd 100644
--- a/src/api.c
+++ b/src/api.c
@@ -1190,12 +1190,15 @@ static int __cgroup_attach_task_pid(char *path, pid_t tid)
if (!tasks) {
switch (errno) {
case EPERM:
- return ECGROUPNOTOWNER;
+ ret = ECGROUPNOTOWNER;
+ break;
case ENOENT:
- return ECGROUPNOTEXIST;
+ ret = ECGROUPNOTEXIST;
+ break;
default:
- return ECGROUPNOTALLOWED;
+ ret = ECGROUPNOTALLOWED;
}
+ goto err;
}
ret = fprintf(tasks, "%d", tid);
if (ret < 0) {
@@ -1214,7 +1217,8 @@ static int __cgroup_attach_task_pid(char *path, pid_t tid)
err:
cgroup_warn("Warning: cannot write tid %d to %s:%s\n",
tid, path, strerror(errno));
- fclose(tasks);
+ if (tasks)
+ fclose(tasks);
return ret;
}