+ PERROR("shmat");
+ return NULL;
+ }
+ DBG("successfully attached buffer memory");
+
+ buf->bufstruct_mem = shmat(buf->bufstruct_shmid, NULL, 0);
+ if(buf->bufstruct_mem == (void *) 0) {
+ PERROR("shmat");
+ return NULL;
+ }
+ DBG("successfully attached buffer bufstruct memory");
+
+ /* obtain info on the memory segment */
+ result = shmctl(buf->shmid, IPC_STAT, &shmds);
+ if(result == -1) {
+ PERROR("shmctl");
+ return NULL;
+ }
+ buf->memlen = shmds.shm_segsz;
+
+ /* open file for output */
+ if(!trace_path) {
+ /* Only create the directory if using the default path, because
+ * of the risk of typo when using trace path override. We don't
+ * want to risk creating plenty of useless directories in that case.
+ */
+ result = create_dir_if_needed(USTD_DEFAULT_TRACE_PATH);
+ if(result == -1) {
+ ERR("could not create directory %s", USTD_DEFAULT_TRACE_PATH);
+ return NULL;
+ }
+
+ trace_path = USTD_DEFAULT_TRACE_PATH;
+ }
+
+ asprintf(&tmp, "%s/%u_%lld", trace_path, buf->pid, buf->pidunique);
+ result = create_dir_if_needed(tmp);
+ if(result == -1) {
+ ERR("could not create directory %s", tmp);
+ free(tmp);
+ return NULL;
+ }
+ free(tmp);
+
+ asprintf(&tmp, "%s/%u_%lld/%s_0", trace_path, buf->pid, buf->pidunique, buf->name);
+ result = fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 00600);
+ if(result == -1) {
+ PERROR("open");
+ ERR("failed opening trace file %s", tmp);
+ return NULL;
+ }
+ buf->file_fd = fd;
+ free(tmp);
+
+ pthread_mutex_lock(&active_buffers_mutex);
+ active_buffers++;
+ pthread_mutex_unlock(&active_buffers_mutex);
+
+ return buf;
+}
+
+int consumer_loop(struct buffer_info *buf)
+{
+ int result;
+
+ pthread_cleanup_push(decrement_active_buffers, NULL);
+
+ for(;;) {
+ /* get the subbuffer */
+ result = get_subbuffer(buf);
+ if(result == -1) {
+ ERR("error getting subbuffer");
+ continue;
+ }
+ else if(result == GET_SUBBUF_DONE) {
+ /* this is done */
+ break;
+ }
+ else if(result == GET_SUBBUF_DIED) {
+ finish_consuming_dead_subbuffer(buf);
+ break;
+ }
+
+ /* write data to file */
+ result = patient_write(buf->file_fd, buf->mem + (buf->consumed_old & (buf->n_subbufs * buf->subbuf_size-1)), buf->subbuf_size);
+ if(result == -1) {
+ PERROR("write");
+ /* FIXME: maybe drop this trace */
+ }
+
+ /* put the subbuffer */
+ /* FIXME: we actually should unput the buffer before consuming... */
+ result = put_subbuffer(buf);
+ if(result == -1) {
+ ERR("unknown error putting subbuffer (channel=%s)", buf->name);
+ break;
+ }
+ else if(result == PUT_SUBBUF_PUSHED) {
+ ERR("Buffer overflow (channel=%s), reader pushed. This channel will not be usable passed this point.", buf->name);
+ break;
+ }
+ else if(result == PUT_SUBBUF_DIED) {
+ WARN("application died while putting subbuffer");
+ /* FIXME: probably need to skip the first subbuffer in finish_consuming_dead_subbuffer */
+ finish_consuming_dead_subbuffer(buf);
+ break;
+ }
+ else if(result == PUT_SUBBUF_OK) {
+ }